Introduction to Ajax with jQuery

Bookmark on del.icio.us

jQuery is a wonderful library and one of it’s best features is how easy it makes working with Ajax. Here Jack will show you exactly how to use jQuery’s Ajax features.

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:

1 <div></div>
2 <form method="post" action="run.php">
3
4 <input type="text" name="name" value="Please Enter Your Name">
5 <input type="text" name="email" value="Please Enter your Email">
6 <input type="submit" value="Submit" id="submitbutton">
7 </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:

1 echo '<h1>';
2 echo $_POST['name'];
3 echo ', your email is ';
4 echo $_POST['email'];
5 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:

1 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></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)

1 $(function() {
2 $('#submitbutton').click(function(e) {
3
4 });
5 });

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

01 var formData = $('form').serialize();
02
03 $.ajax({
04 type: "POST",
05 url: "run.php",
06 data: formData,
07 success: function(d) {
08
09 $('div').empty().html("hi " + d);
10
11 }
12 });

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:

1 type: "POST", //can be POST or GET, depending on which method you are using
2 url: "run.php", //relates to the php file we created earlier.
3 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:

1 e.preventDefault();

And that’s it.

Done!

Here is the entire jQuery code:

01 $(function() {
02 $('#submitbutton').click(function(e) {
03
04 var formData = $('form').serialize();
05
06 $.ajax({
07 type: "POST",
08 url: "run.php",
09 data: formData,
10 success: function(d) {
11 console.log(d);
12 $('div').empty().html("hi " + d);
13
14 }
15 });
16 e.preventDefault();
17 });
18 });

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

  1. No comments yet.

  1. No trackbacks yet.