go top

MEGA Sale

  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

jQuery Ajax Form

Sunday, 27th January, 2013  /  Javascript Tutorials  /  5 Comments
If your website has some forms, you should consider using Ajax. Ajax allows the user to receive immediate feedback when the submit they form without ever leaving the page. Using Ajax can clutter your JavaScript, so I highly recommend using jQuery's Ajax function, which means you will need the jQuery library. The jQuery Ajax function has massive amount of useful features that you can use to customize your Ajax calls for your users. Using jQuery, you will not have to flood your Ajax function with a mountain of if statements as they are built into the function for you.

One possible form that you might consider using Ajax is a comment form. Users love to see their comments immediately posted without having the page reloaded for them. Ajax is still somewhat confusing for users, which means you need to build in a few strong feedback mechanisms. First, let's build a really simple contact form with just a username field, comment field, and a submit button.


<div>Comments</div>
<form id="commentForm" action="comment-post.php" method="POST">
<input id="commentUsername" type="text" name="username" /><span id="commentUsernameError">sdfasdf</span>
<br/>
<textarea id="commentComment" name="comment"></textarea><span id="commentCommentError">sdfdsfa</span>
<br/>
<input type="submit" id="commentSubmit" name="action" value="Submit" onclick="return false;" />
<div id="commentFeedback" style="display:none;"><img src="loading.gif" /></div>
</form>


The important thing about the previous form is to see the build in feedback spans and div. Each form element has a span associated with it, so that when a user creates an error in that field, you can show them where the error occurred. Our submit button has an "onclick" attribute set to "return false", which means to not submit the form. The beauty of placing that JavaScript inside the form is that the form will work even if JavaScript is not enabled. Finally, we have the "commentFeedback" div with a "loading.gif" inside. This is a feedback mechanism that shows the user that the website is processing their data. Now we can move onto the meat of this tutorial, the jQuery Ajax.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$("#commentSubmit").click(function() {
var passValue = 0;
var formJSON = $("#commentForm").serialize();
$("#commentSubmit").attr('disabled','disabled');
if ($("#commentUsername").val() != "") {
$("#commentUsernameError").html('');
passValue++;
} else {
$("#commentUsernameError").html('Please enter your username');
}
if ($("#commentComment").val() != "") {
$("#commentCommentError").html('');
passValue++;
} else {
$("#commentCommentError").html('Please enter a comment');
}
if (passValue == 2) {
$("#commentFeedback").html('<img src="loading.gif" />');
$("#commentFeedback").show();
$.ajax({
type: "POST",
url: "comment-post.php",
data: formJSON,
success: function(){
$("#commentFeedback").html('Comment posted');
},
error:function(){
$("#commentFeedback").html('Could not post your comment');
}
});
}
$("#commentSubmit").removeAttr('disabled');
});
</script>


The majority of this example is validation. We set up a "passValue" variable that tells us that if both fields have valid data, we can submit the form. This allows our server to relax while the browser does all of the validation before sending the data (You should ALWAYS validate the data on the server side as well). After creating our "passValue" variable, we serialize our form data so that we can access it easily later in the function. Next, we disable the submit button so that the user will not keep trying to submit.

We follow that up with a series of validation tests to finally arrive at our "if (passValue == 2)" statement. First, we show our "loading.gif" so the user knows the website is processing. Next, we launch the Ajax function that can take some properties like type, url, data, datatype, and a series of feedback functions. Our type is "POST" because it is a form that is submitting data to the server. The url is the same as the form's action url. The data is the form data that we serialized in the second statement. Then comes the awesome success and error functions. Success is when the request completes successfully, so we want to tell the user that the comment was posted. Error tells the user that something messed up.

At the end of our JavaScript, we enable our submit button in case the user wants to add additional comments. That covers how to use jQuery's Ajax function to create more useful form elements, while allowing those without JavaScript to also be happy. You can easily implement this code by changing the code inside the "success" and "error" functions. Go out there and create some Ajax compatible forms!
Share on:

5 Comments to "jQuery Ajax Form"

anthony

anthony / April 28, 2015 at 20:48 pm

Very fantastic, standard, and professional scripts. Well trusted.

nouaman

nouaman / January 11, 2015 at 20:07 pm

just great

Andrei

Andrei / November 3, 2014 at 12:47 pm

i have another solution for this form with jquery :) easy and eficient!

first step need jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

next step need to make form... an example is this:

Create index.php



echo <<<JAVASCRIPT
<script>
$(document).ready(function() {
$('#form').ajaxForm({
target: '#Result',
success: function() {
$('#Result').fadeIn('slow').delay(4500).fadeOut('slow');
}
});
});
</script>
JAVASCRIPT;


echo '
<div id="Result"></div>
<form action="ProcessAjax.php" method="POST" id="form">
<input type="text" name="yourName">
<input type="submit" name="submit" value="Send">
</form>';


Create ProcessAjax.php

if(isset($_POST['submit'])) {
echo "Hello, ".$_POST['yourName'];
}


seriosly... it's easy with that method :)

Navneeth

Navneeth / September 12, 2014 at 21:36 pm

The scripts in this website are superb all are working beat website for Web Developers with secure php scripting coding

daljindersingh

daljindersingh / September 8, 2014 at 05:46 am

it is great website

Add your comment

Captcha

    Please, be polite and helpful and do not spam or offend others! We promise you will be treated the same way!

    Log in to your account to post your comments. If you still haven't joined our community yet, you can create your FREE account now!

    Posting tip:
    If you use code in your comments, please put it in these tags [php], [sql], [css], [js] PHP code example: [php] echo date("Y-m-d"); [/php]

    Thank you,
    PHPJabbers Team

    PHP Scripts

    Check our extensive collection of top-notch PHP Scripts that will enhance your website!


    Commercial PHP scripts

    Free Scripts

    Add great new functionalities to your website with our Free Scripts collection.


    Free scripts