Fork me on GitHub
RSS
 

AJAX Form Tutorial

12 Oct

This tutorial will show you how to create an AJAX form with PHP and jQuery. The AJAX form doesn’t look any different to an ordinary HTML form, with the exception of making sure that when we submit the form, it calls a javascript function rather than pushes the user to a page (causing a new page reload). I’ll also demonstrate how we can use ‘loading’ animation for the AJAX form, whilst we wait for the server to respond.

DEMO: HERE

The AJAX Form

<form name="ajaxForm" id="ajaxForm" method="post" action="" onsubmit="postForm(); return false;">
	<label for="yourName">Your Name</label> 
	<input type="text" name="yourName" id="yourName" />
	<br />
	
	<label for="yourAge">Your Age</label> 
	<input type="text" name="yourAge" id="yourAge" />
	
	<br />
	
	<label for="submitForm">&nbsp;</label> 
	<input type="submit" id="submitForm" value="Submit" />
	
	<input type="hidden" name="formPosted" value="true" />
</form>

We’re using a simple form for this tutorial, but feel free to add any number of form elements you wish. In this example, we have given the form an id of ajaxForm, we also have a field for yourName and a field for yourAge. As explained in my User Login Script tutorial, we also have a hidden field that I like to use to confirm that the page was actually submitted, and which form was the “sender”. The most important thing about this form, and to make it work using AJAX, is the following attribute within our opening form tag:

onsubmit="postForm(); return false;"

The onsubmit attribute allows us to execute some JavaScript (to eventually run our AJAX!) prior to actually sending the form using it’s default method (by sending the form data to the page via a complete page reload). We’re immediately calling return false; straight after, this actually prevents the form from sending the data the normal way.

If it helps to understand, here’s all we’ve done up to this point:

  • Create a simple HTML form
  • Add the onsubmit attribute to the opening form tag
  • Made a call to a (currently non-existent) JavaScript function within the onsubmit attribute
  • Returned false after our call to the JavaScript function – to prevent the form from actually submitting

The AJAX Preloader

Our form is all dealt with, so now let’s create a little div, which will show when our form is sending the data, and waiting for some response back. After your form, add the following:

<div id="loading" style="display: none;">
	<img src="loader.gif" style="vertical-align: middle;" /> Loading...
</div>

This is a real simple little div, which is hidden by default (using the style=”display: none” attribute). We’ve given it an id of loading, which is important as we’ll need to use the jQuery to show / hide this div in a moment. Inside this div I have placed a preloading gif which I created using http://www.preloaders.net, and a simple bit of text saying ‘Loading…’. You can put whatever you like within this div really, but I quite like the preloading animated gifs myself.

The Actual AJAX Function

Ok, so we’re diverting the actual onsubmit action of the form to a JavaScript function called postForm(). We’re using jQuery to handle this AJAX form as it’s a much easier method than manually writing a cross-browser XMLHttpRequest handler. I’m assuming you know how to include jQuery into your page, but if not – take a quick peek at my Textarea Counter tutorial, which explains my preferred method for including jQuery libraries.

Right, you have jQuery included? Good, let’s go and create the postForm() function now. It looks like the following:

function postForm(){
	$('#loading').show('fast');
	$.post("index.php", $("#ajaxForm").serialize(),
	   function(data){
			$('#loading').hide('fast');
	     alert("Your name is: " + data.name + "\nYour age is: " + data.age);
	   }, "json");
}

The first thing we’re doing is showing the loading div (with our preloader). We do this by calling:

$('#loading').show('fast');

This does a quick fade-in of our loading div, before we do anything else. This is a good idea, because we want to give the user immediate feedback that something it happening. We could also disable the submit button at this point – but that’s not covered in the scope of this tutorial.

Next comes our actual AJAX call which will submit our form. I’m using $.post() in this tutorial, but you can use $.get() and even $.getJSON().

  • $.post() will simulate a form POST (as if we had our form method set to post)
  • $.get() will simulate a form GET request (as if we had our form method set to get)
  • $.getJSON will simulate a GET request as above, but expect the results to be well formatted JSON, and as such return it as JSON data

A quick look at the jQuery docs for how the $.post() function should be formatted shows that we can use numerous methods, but for this tutorial we want to set four main things.

The page we’re submitting the form data to. As explained in my User Login Script tutorial, I like to submit the data to the same page, so this is going to be set to index.php (and we’ll get to how we handle the data in a moment!).

Next, we need to tell the AJAX call what data we’re going to be sending. As we’re using a well-formatted form (when using AJAX, you won’t always necessarily be using a form), we’re going to use a great jQuery function called serialize() which – in basic terms – tells our function that we’re sending all elements within the form that we’re serializing. We do this by calling $(“#ajaxForm”).serialize() (essentially, we’re serializing all the data within the ajaxForm – remember, this is the ID of the form we created earlier).

After that comes our “success” function. In other words, a function that gets automatically called once our AJAX call has had a response from the page that we’re sending the data to. This is taking an automatic parameter which I’ve called data. You can name this parameter anything you like (provided it’s not a reserved JavaScript word), but generally speaking – data is a good enough keyword, as essentially what we’ll be receiving is data.

We’ll break down that mini-function in a moment.

The fourth and final parameter that we need (for this tutorial anyway) is the “what data type are you expecting back?” parameter. I’ve set this to json as I like working with it. What is JSON? Ah, it stands for JavaScript Object Notation. It is a relatively modern, and my preferred method, for handling data within JavaScript. If you’re used to PHP, think of JSON as a multi-dimensional array. It allows us to handle groups of data as one “object” (or variable if you prefer). We generally use dot notation to access it’s properties. I’m sure I’ll explain JSON in greater detail in the future – but for now here’s a more-than-generous explanation.

Ok so our four parameters are set:

  • Send Data To This Page
  • Send This Data To That Page
  • Run This Function When We Get a Response From That Page
  • I’m Expecting The Data To Be Returned Like This

Ok so that’s our four main parameters set for our $.post() function. Before we check out the server-side handling of this AJAX call, let’s just take a quick peek at our success function (which is our third parameter in our AJAX call):

function(data){
	$('#loading').hide('fast');
	alert("Your name is: " + data.name + "\nYour age is: " + data.age);
}

The first thing we’re doing is hiding the loading div (as our data has now loaded), and then we’re just doing a simple alert with the data we received. To populate the alert, we’re just using JSON to retrieve the data using data.VARIABLE. In this case, data.name and data.age.

How do we know we’re going to have name and age sent back as our data JavaScript Object? That all comes down to the final part – the server-side handling of our AJAX form, and I think you’ll be surprised to see just how simple it really is!

Handling the AJAX Form, Server-Side

At the very top of our page – where I like to handle my form posts (on the same page as the form, not on a different page), we have the following code:

<?php
if($_POST['formPosted'] == 'true'){
	$returnData = array(2);
	$returnData['name'] = $_POST['yourName'];
	$returnData['age']	= $_POST['yourAge'];
	echo json_encode($returnData);
	exit;
}
?>

That’s it!

We know that we can handle the form variables using the $_POST super global, as we used the $.post() function via jQuery. We also know that we’re sending ALL form elements, because we used the serialize() method, again provided by jQuery. This means that we can access the yourName and yourAge form elements (note that we’re also checking that formPosted is true before running this block of code – this was our hidden variable in our form remember?).

We’re then simply (and very simply for the purposes of this tutorial), creating an array called $returnData, and adding the value of yourName to $returnData['name'], and yourAge to $returnData['age']. Notice something here? The PHP array we have just created now has two elements, name and age.

All we need to do now is to encode our array as JSON, and echo it out, which we do in one line:

echo json_encode($returnData);

Then most importantly, we exit. We MUST exit here, otherwise the remainder of the page would continue to load, and also be sent back to our JavaScript function which is waiting for the data. ALWAYS exit once you have dealt with an AJAX call. The point is to provide the data requested and that’s it. If we sent it all back, it would malform the JSON we’re echoing out, and as such, break our functionality. Not to mention it’d also be completely pointless, as we’re loading the entire page again!

So there you have it! Any questions, comments or criticism – please post in the comments, and don’t forget that there’s a:

DEMO: HERE

 
 

Tags: , , ,

Leave a Reply

 

 
  1. Josh

    February 1, 2011 at 12:01 am

    Great tutorial and nice elegant solution mate, I like it a lot!

    I just have one question though, how would you handle a browser with no javascript / js turned off? Could we have an action=”old_school_method.php” to catch those users? or would that override the onsubmit, maybe remove the action with JS onload to workaround that? feels clumsy though!

    Nice work in any case, this will be a great help for me today :-)

     
    • Mizo

      March 21, 2011 at 9:42 am

      @josh , you should first check if client browser supports js or not , each case should hold piece of code related with .

       
  2. 5 Tutorial su Ajax (jQuery+PHP) - Oriodesign

    February 18, 2012 at 10:43 am

    [...] Tutorial su Ajax (jQuery+PHP) February 18th, 2012 | Posted by oriodesign in Uncategorized Ajax form tutorial Un interessante tutorial per inviare dati in post da un form alla stessa pagina gestendoli con [...]

     
  3. songchochrist

    August 9, 2012 at 5:23 pm

    Thanks alot.

     
  4. leah

    December 11, 2012 at 4:22 pm

    test

     
  5. Farid Abbas

    January 11, 2013 at 5:44 am

    Thank you so much Sir for posting such a great tutorial for people like me. I got first touch on JSON. Best guides for ajax
    Main points that I learnt from this tutorial.
    AJAX , .post (1,2,3,4) , return false in Form, serializing( that is provided by jquery), Json_encoding, and exit.
    I hope i’ll get the best response if found any problem in future.

     
  6. ABc

    May 7, 2013 at 6:42 pm

    comment

     
  7. shanky181189

    October 8, 2013 at 7:38 am

    test

     
  8. wewtert

    December 17, 2013 at 7:12 pm

    twerte