Jay Blanchard, LLC

Website & Web Application Development & Design

the Basics of jQuery AJAX

April 2015

  • Required: a webserver on which to test the code. I use PHP in the examples, you can use the server-side language you're comfortable with.
  • Nice to know: HTML, jQuery basics
  • Download: Project Files

AJAX (Asynchronous JavaScript And XML) is a great tool but there is so much confusion about how to use it. In this tutorial I'll cover how to use jQuery's AJAX functionality in its most basic form. This basic form will get most developers through 90% of any project requirement. In later tutorials I'll cover advanced jQuery AJAX techniques.

At the heart of the matter AJAX initiates a request (HTTP or HTTPS) to the server, much like you would do with a link to go to a page somewhere on the web or the click of a submit button which causes the browser to be redirected to another page. The page would be delivered to your browser and displayed. AJAX changes the game.

Instead of the browser navigating to the page in question AJAX sends a request to the page and the page returns some data back to the AJAX handler. On the client-side, if done correctly, the page in the browser is not reloaded. Instead, the data returned from the server-side is used in the page from which the AJAX request was sent.

Having thought about it, the process does sound a little confusing. We have a page loaded into our browser. The page stuffs a note in an envelope and sends the note to the server (the request). The server opens the envelope and does something with the information in the note. The server stuffs a note into an envelope and sends it back to the browser (the response) even if you have not asked for anything from the server.

The entire process is asynchronous meaning the client (browser) will send the request when it is good and ready. Likewise the server responds whenever it likes. This means you need to be careful about when you expect a response and when you actually use the response.

Let's setup a simple example, a counter the increments each time you click a button. First the PHP:

                    <?php
                    $currentNumber = $_POST['currentNumber'];

                    function increment($currentNumber) {
                        $newNumber = $currentNumber + 1;
                        return $newNumber;
                    }

                    echo increment($currentNumber);
                    ?>
                

Save the file on your server as counter.php.

AJAX expects text (XML, HTML, JSON or text) to be returned so you must echo the text just as if you were accessing the page without AJAX.

Now create a web page called counter.html with the following markup:

                    <!DOCTYPE html>
                    <html>
                    <head>
                        
                        Click Counter
                        
                        
                    </head>
                    <body>
                    </body>
                    </html>
                

You'll notice I have included a link to a CDN (Content Delivery Network) for the version of jQuery I am using. I have coupled the CDN requests with a fallback to a local copy of the jQuery just in case something goes wrong with the CDN.

Add the following markup to the body section:

                    <div id="currentNumber">0</div>
                    <button type="button">Click To Add One</button>
                

The HTML is now complete. If you load the page into your web browser from a web server (you'll need a web server to run AJAX because it will be making HTTP requests) you will see the number zero and a button. Clicking the button does nothing at this point because there is nothing to handle the click event.

Normally I would recommend putting JavaScript and jQuery code in separate files to be included in the page. In this case, because it is just a simple example, we'll add our jQuery into a pair of script tags.

                    <script type="text/javascript">
                    $(function(){
                        $('body').on('click', 'button', function(event){
                            event.preventDefault();
                            var currentNumber = $('#currentNumber').text();
                            $.ajax({
                                method: 'POST',
                                url: 'counter.php',
                                data: {currentNumber : currentNumber}
                            })
                            .done(function(newNumber){
                                $('#currentNumber').text(newNumber);
                            });
                        });
                    });
                    </script>
                

Place this entire section of code, including the new script tags, just below the script tags you have in your HTML file. Save the file and place on your web server in the same folder as the PHP file you created earlier. Load the HTML file into your web broswer and click the button. Did the number on the page change? If not I'll show you how to check for errors later on. First let's examine the jQuery code line-by-line.

The first line of jQuery takes any button click event and delegates it to the body tag. Why did I use event delegation here? It was just a personal choice because I might add other buttons dynamically. I also pass the event to the function.

                    $('body').on('click', 'button', function(event){
                

The second line takes the click event and prevents any default behavior the click may try to perform. This is especially handy for anchor links and form buttons (submit and reset).

                event.preventDefault();
                

The next order of business is to capture the number in the div on the page and place it in a variable.

                var currentNumber = $('#currentNumber').text();
                

The next section of code calls jQuery's AJAX function* and generates the request. I set this up as a post request to the PHP file we created earlier. The data I am sending is our variable for the current number and I have named it 'currentNumber' and it should be part of the $_POST array if the AJAX request works properly.

                $.ajax({
                    method: 'POST',
                    url: 'counter.php',
                    data: {currentNumber : currentNumber}
                })
                

We set up the code for the response next. Because we're just asking for a new number I have named the variable which should contain the response to make it clear. Many times you will see the variable with a more generic name like 'data' or 'response' because it will contain more information and may have to be parsed in a special way to facilitate its use. We chain the 'done' method to our AJAX call and use the returned number to update the div on our page.

                .done(function(newNumber){
                    $('#currentNumber').text(newNumber);
                });
                

Where do we go to troubleshoot things if all of this doesn't work? Fortunately every modern browser has a set of developer tools. The most important tool in the group, for a JavaScript developer, is the console. Most browsers activate the developer tools when you press the F12 key.

Before I created the counter.php I loaded the HTML into my browser and clicked the button. The error, page not found, was reported quite clearly.

I added the counter.php file. You can look at the request by clicking one tab -

You see the response by clicking another -

Next I introduced an error into the PHP file and received a response concerning the error -

Just one more error. I made a change in the PHP making it send an internal server error header back to the AJAX response handler and I extended the AJAX to handle failures more gracefully. Chain the fail method to the end of the AJAX function:

                $.ajax({
                    method: 'POST',
                    url: 'counter.php',
                    data: {currentNumber : currentNumber}
                })
                .done(function(newNumber){
                    $('#currentNumber').text(newNumber);
                })
                .fail(function(message){
                    $('#currentNumber').text('there has been a problem');
                });
                

When the button is clicked the console reveals the error and the message is output to the div on the page. Just as you might do with other functions you can use the fail method to fire off a number of complex interactions from making your user's experience better to keeping you informed of when problems occurred and what happened during the process.

Once you understand basic AJAX with jQuery it opens up a world of possibilitites to you. You can easily get information from and update databases, create custom interactions and much more. Knowing how to troubleshoot your AJAX requests by using the console will cut down on your development and bug squashing time, allowing you to get your web sites and applications rolled out more quickly.

* jQuery provides some other shorthand methods, such as $.post() and $.get() which will handle basic AJAX requests very efficiently. The purpose of the tutorial is to learn and understand the low-level AJAX method in practice.

Comments? Shoot me your thoughts on Twiiter: @jaylblanchard