Introduction to Ajax with jQuery

jQuery is one of the most popular javascript frameworks out there and for good reason. It has a plethora of features that make it a pleasure to work with. One of these is Ajax. Ajax is a way of sending information to the browser and retrieving it without loading the page. So, we can use this when we submit a form, everything happens without the page refreshing. With normal javascript this is nothing short of a nightmare but with jQuery it’s much easier. For this lesson’s purpose I’ve created a simple form that asks the user for their name and password, and will then display it on screen. However, whatever you want to do with the data, the Ajax is exactly the same.

So here is my HTML form, nothing fancy at all:

	<div></div>
	<form method=&quot;post&quot; action=&quot;run.php&quot;>

		<input type=&quot;text&quot; name=&quot;name&quot; value=&quot;Please Enter Your Name&quot;>
		<input type=&quot;text&quot; name=&quot;email&quot; value=&quot;Please Enter your Email&quot;>
		<input type=&quot;submit&quot; value=&quot;Submit&quot; id=&quot;submitbutton&quot;>
	</form>

You’ll notice a small amount of PHP in there which is used to display the user’s name and email. It is important to remember that before we add the jQuery we must make sure the form works without it. The empty div is for displaying the data using jQuery. I’ve also created run.php, which will display the user’s information:

	echo '<h1>';
	echo $_POST['name'];
	echo ', your email is ';
	echo $_POST['email'];
	echo '</h1>';

You could have all of those in one echo statement, but for clarity I’ve split it over multiple lines. If you run it now, you will see when you add your data and click submit it takes you to a new page which shows what you entered. So our form works now, without any jQuery. Now we can look at making it work using Ajax. Hoorah!

The Ajax

So our first step is to include jQuery. I suggest you use Google’s CDN to do this like so:

<script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot; type=&quot;text/javascript&quot; charset=&quot;utf-8&quot;></script>

Select the Button

Now we need to tell jQuery only to run when the DOM Is loaded, and then select our submit button (which, if you check the HTML, I gave an id of “submitbutton” so we could easily select it)

	$(function() {
			$('#submitbutton').click(function(e) {

			});
		});

You might notice that I’m passing a variable ‘e’ in. e represents the event, which in this case will be a mouse click. So the variable ‘e’ contains loads of information about the mouse click and also a nifty function which we will use later.

Setting Up the Ajax

var formData = $('form').serialize();

				$.ajax({
					type: "POST",
					url: "run.php",
					data: formData,
					success: function(d) {

						$('div').empty().html("hi " + d);

					}
				});

There you have all the code that makes up our Ajax request. First we use jQuery’s serialize() function. This gets the data from the form so we can then use it, and so we can use it later we save it to a variable called formData. Once this is done we create a new instance of jQuery’s ajax object and set up various parameters which I shall explain below:

type: "POST", //can be POST or GET, depending on which method you are using
url: "run.php", //relates to the php file we created earlier.
data: formData, //the data we are passing through

Success!

Now we need to create a function to actually display the data. We name this success (it must always be called this) and all we do is select ourdiv, then empty it, before adding the word “hi”, followed by a variable “d”. If you look, you’ll notice I passed in a variable “d” into our success function. This variable stores whatever was returned from the call. So all we then have to do is echo it out.

One last Thing

Remember we passed the variable ‘e’ in at the very beginning? We did this because we need to actually disable the default action for the submit button. If we don’t do this then the submit button will just act like normal and refresh the page and do what it normally does. It’s really easy though, just one line:

e.preventDefault();

And that’s it.

Done!

Here is the entire jQuery code:

$(function() {
			$('#submitbutton').click(function(e) {

				var formData = $('form').serialize();

				$.ajax({
					type: "POST",
					url: "run.php",
					data: formData,
					success: function(d) {
						console.log(d);
						$('div').empty().html("hi " + d);

					}
				});
				e.preventDefault();
			});
		});

Time to test it, load it up, fill it out, click submit and you should see it change without refreshing the page. Voila! We are finished.

Demo

7 Comments on "Introduction to Ajax with jQuery"

  1. cypherbox says:

    Great post Jack. Very useful! thanks.

  2. MikeHopley says:

    You’re building up a solid collection of Jquery tutorials, Jack.

    I like how you explain things; you keep it simple, omitting bluster without omitting details. I will probably come back to this tutorial when I want to get started with AJAX. :)

  3. Jack Franklin says:

    Hi Cypherbox, thanks very much for your comment.

    Mike – glad you like them all :) jQuery is such an awesome thing to work with but often I think some people find it so simple they don’t explain it to the level that I personally like things explained to, so I try and make sure I include absolutely everything.

    Glad you enjoyed the tutorial guys :)

  4. Robert says:

    I just stumpled upon Web Squeeze and I must say that it is chaulk full of usefull web tutorials especially with the AJAX tutorial here.

    Not only did I want to learn more but as a side bonus learned about jquery through using a CND. Never thought about that one.

    Keep them coming.

    Cheers

    Robert
    Alberta, Canada

  5. Mark says:

    Great tutorial Jack. I am glad to find this kind of great work out on the web that gives you an easy introduction into jQuery and Ajax without proper prior knowledge.

    There is one thing though. I tested it in FireFox 3.6 where it worked fine. However when I went to IE8, it didn’t produce the desired result and gave the error:

    Webpage error details:
    Message: ‘console’ is undefined
    Line: 18
    Char: 11
    Code: 0
    URI: http://localhost/forms/form.html

    Perhaps it’s my own settings, or this script has an issue with MS IE8. Thought I should let you know.

    Keep up the good work!

  6. Mark says:

    Fixed the above described problem by commenting out: console.log(d);

    I noticed that the code snippets did not contain that line, but the ‘end result’ did.

  7. James.H says:

    It’s always not easy to tell whether an image has been manipulated. However, Photoshopped Image Killer makes things easy. By submit an image URL you can see if the image has been altered. Altered image will get a red flag while original image gets a white flag.

Got something to say? Go for it!