Validate HTML form using ajax request to another page - javascript

I want to use another page of my site to validate HTML form input. If the input is NOT valid, I want to show an error somewhere on my form page without reloading. And otherwise, if it IS valid, I want to submit the form normally.
After reading similar SO questions, I didn't found any exact solution, but actually invented my own, which works for me. Though, I still think that my solution is a bit weird, so I'm asking for proper ideas.
HTML:
<form id="form" method="POST"> ... some inputs ... </form>
<button id="submit" type="submit">Save</button>
<p id="errors"></p>
JS:
$('#form').submit(function (event) {
var formData = $(this).serializeArray();
event.preventDefault();
$.ajax({
type: "POST",
url: '/validate/',
data: formData,
success: function(data) {
if(!data)
{
$('#form').unbind('submit');
$('#submit').trigger('click');
}
else
{
$('#errors').text(data);
}
}
});
return false;
});
NB: It works as expected, I'm asking for better solutions.

Related

jQuery Ajax loop on form submit

New to Ajax, however, I can't figure out what is wrong, and I assume its the Javascript. My php page is working just fine, however, with this code my login Html simply refreshes over and over with the end of the url changing to ?username=whatIenter&password=whatIenter
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('#login_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/lib/login.php',
data: $(this).serialize(),
success: function(data)
{
alert("WORKED");
}
});
});
});
</script>
HTML
<form id="login_form" action="" method="POST">
<input type="text" id="user" name="username">
<input type="password" id="pass" name="password">
<button id="loginButton" class="login_submit" type="submit" >Login</button>
</form>
First of all, which jQuery version are you using?
Your code is working fine with jQuery 3.3.1
Always keep in mind this good practices:
Disable the cache on your browser while you develop
Each time you wanna check your site, open the browser console and then press F5
Javascript code always needs to stay at bottom inside body tag (just before </body>)
This also apply in the case you put it on a separated file (recommended)
Set the action parameter on your form, this can prevent unexpected errors
Even if you are gonna call the same file or url
Try:
var header = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
};
var request = $.ajax({
url: '/lib/login.php'
,data: $(this).serialize(),
,headers: header
});
request.done(function(response) {
alert("WORKED "+response);
});
The thing is, some/most API's will require you to explicitly specify the content type, before they return the "standard" HTTP response that your Javascript will read.
Resources:
https://web.archive.org/web/20210816145541/https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

Making ajax call from submit id

I have a form in which currently posts to a hard coded php page in the action of the form, this works fine, it posts to the DB no problem, but where things get tricky for me is I don't want to post to a new page so I have opted to use ajax. So I got rid of the action field from the form and put in some jquery to make an ajax call. the issues I am having is well..it doesn't work :D. Could someone take a look at my js file and explain to me what I am doing wrong or what I should do?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form>
<p>Comment</p>
<textarea name= "comment" rows="6" cols="50"></textarea><br />
<input type="submit" name= "submit" value="submit" id = "submit">
</form>
$('#submit').on('click',function(){
$.ajax({
type : 'POST',
url : 'comment.php',
data : formData,
dataType : 'json',
})
});
You should handle the 'submit' event of the form over the 'click' event of the submit button. You should also return false; at the end of function to prevent the form from posting to a new page. You are handling the submit yourself. Also I would put the action attribute back on the form element for the rare occasion that JavaScript is disabled on the client. Give the form an id and target that. Your code is correct otherwise.
HTML
<form id="my-form" action="comment.php" method="post">
<!-- input fields -->
</form>
JavaScript
$('#my-form').on('submit', function(){
// code...
return false;
});
Providing the action attribute, as well as the method attribute, on the form element will make these available to access in your submit handler as well as providing a proper fallback for any JavaScript failures. That may not be necessary for this instance but may be helpful in the future.
Your handler could now look something like this:
JavaScript
$('#my-form').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type : this.method,
url : this.action,
data : formData,
dataType : 'json'
})
.done(function (data) {
// do some stuff with 'data'
})
.fail(function (error) {
// do some stuff with 'error'
});
return false;
});

Should I combine PHP with ajax to post data to the server?

Imagine the page always refreshes after submitting a comment form. That is annoying since the comments are at not at the top of the page and you always have to scroll to the bottom to see your comment and the other ones.
I thought it would be a lot better to use ajax to submit the form.
HTML
<form id="com-form" method="post">
<textarea type="text" name="text" required=""></textarea>
<input type="submit" value="Post"/>
</form>
<div id="com-refresh"></div>
jQuery
$("#com-form").on('submit', function(e) {
e.preventDefault();
var form = $(this),
form_data = form.serialize();
$.post('/php/comments/add.php', form_data, function(data) {
$("#com-refresh").append(data);
});
});
PHP
<?php
session_start();
require_once 'comment.class.php'; //require a class with methods
$text = $_POST['text'];
if($_SESSION['status'] == 'loggedin') {
if(isset($text)) {
$comment = new Comment(); //initialize the Comment object
echo $comment->add_comment($text); //safe the comment in the database and output it
} else echo "Your comment is empty.";
} else echo "Please log in to post comments.";
I hope the code is understandable.
Do you think it is smart or a bad practice to use ajax to not refresh the page after submitting a form?
How should it be done? Do you have a better idea, a cleaner solution?
You could simply do:
$(document).ajaxSuccess(function(e, xhr, settings) {
$(".mydiv").html(xhr.responseText);
});
having your php file print what ever html you want to replace.
further reading: ajaxSuccess
example of what might be your solution
form file:
<form method="post">
<textarea type="text" name="comment" id="com-area"></textarea>
<input type="submit" id="com-submit"/>
</form>
<div id="com-refresh">
<?php require_once "comments/build.php"; ?>
</div>
$(function() {
$(".cmtx_form").submit(function(e) {
e.preventDefault();
var form = $(this);
var text = $(".cmtx_textarea_field").val();
$.ajax({
type: 'POST',
url: 'comments/add.php?ajaxCall=true',
cache: false,
data: { comment: text }
});
});
});
$(document).ajaxSuccess(function(e, xhr, settings) {
$("#com-refresh").html(xhr.responseText);
});
your add.php file should look somewhat like so:
// ... code code code...
if (isset($_GET['ajaxCall']) && $_GET['ajaxCall']) {
include_once('/path/to/build.php');
}
simply you can redirect the file from add.php to build.php after complete the process using header('location:comments/build.php'); or some other else, so second ajax call was unnecessary.
The problem was the php code. I have rewritten the functions that generate the comments in OOP style which helped a lot. I edited the post know so it can be useful in the future.
To make it short:
Use ajax! Your website's user experience will be a lot better, because you are able to provide live updates, etc.
It is recommendable to use the built-in jQuery function .serialize() to safe data into a "text string in standard URL-encoded notation", that can make your work more simple.
I know there is a lot of discussions about OOP, but it really helps understanding, organizing and maintaining your code more easily

Login to a site without redirect to that site using jQuery/ajax

I want to send a login form to a site without having the page redirect to that site but rather just display a blank page instead. I have been looking around and noticed jquery would help me with this but I haven't found a way to get it to work quite right so I was hoping for some advice. This is what I have right now.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="placeholderurl" method="post">
<input type="hidden" name="username" value = "placeholder"/>
<input type ="hidden" name="password" value = "placeholder"/>
<input type="submit"/>
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
var formdata = $('#myForm').serialize();
$.ajax({
url: "placeholderurl",
type: "POST",
data: formdata,
cache: false,
success: function(data) {
alert("yeah");
//?code to display blank page after successful login??
},
error: function(){
alert("noo");
}
});
});
});
</script>
</head>
</html>
Currently, the code always goes into the "noo" error block. I'm not sure how to extract more information out of the error so I don't know exactly what is going wrong. Any advice/tips would be appreciated.
*Edit
The placeholderurl and placeholder are filled in with the correct information in my actual code. Also, the url I want to post to is not in the same domain as the function is being called from so ajax may not work for this(comment from Archer). Since this is the case, is there another way to get the desired behavior that I can try without using ajax. Thanks again.
I'd suggest watching your network traffic in something like Fiddler, Firebug, or Chrome's developer tools and see what the response is that is causing the error. I'm guessing your placeholderurl is on a different domain and your call is failing due to that.

How to make a search form using jquery and razor

I have made an CRUD application using webmatrix. I am using jquery and razor syntax. As I am still learning, took me long to figure out how to use jquery and implement it in my asp.net.
Below is the code I have done:
$('#grid').click({
function () {
$.ajax({
type: "POST",
//javascript code here
</script>
</head>
<body>
input type="text" name="fname"><<input type="button" value="Submit form">
<div id="grid" class="ui-widget">
#RenderPage("~/Partials/Recipient.cshtml")
</div>
I am interested in a way where when I click the submit button the value in my text box is posted to my Recpient.cshtml and executed, Then it is rendered underneath the search.
I am stuck here where I need to post the input value to Partials/Recipient.cshtml.
First you configure your ajax call (which would send the value of your fname input field as a POST parameter to your Recipient.cshtml script), then process Recipient.cshtml output on success.
It should look like:
$.ajax({
url: "Partials/Recipient.cshtml",
type: "POST",
data: { fname: $('input[name$="fname"]').val() }
success: function(ajaxoutput)
{
//dosomething();
}
});
More info: http://api.jquery.com/jQuery.ajax/

Categories