A Pratical Guide to Using AJAX in Web Apps

Published 1st February 2010

I have been doing a lot of work recently on MakeSomeTime and my final year Uni project (which is a web app) and both use a substancial amount of AJAX to power them. So what I want to do here is build on a previous article and outline a practical solution to using AJAX in your web apps using, in this case, jQuery and PHP.

Prerequisites of Sorts

This is not a beginner topic and I am going to assume you have a sound knowledge of Javascript, PHP and what AJAX is. Also a knowledge of the jQuery library will help but is not essential to the understanding of what is going on here. Rather controversially I am also going to be using JSON as the data exchange format rather than XML (despite the fact that the “X” in AJAX stands for XML) so you will need to know what JSON is. Now if your sitting comfortably we will begin.

The Motive

We want UI’s to be interactive, fast and slick. We don’t want to have to wait for re-loading pages when we submit a form. We want to click a button, have a nice message saying that it’s doing something, we want the page to update in an elegant way and then we want it to get out of the way. That’s why we use AJAX and Javascript. We still have the same HTML and PHP code that we would have otherwise used. The difference is that now we throw Javascript on top and just like magic, we have a slick UI. So how do we do this in a simple and maintainable way? Keep reading.

The HTML

Lets start simple. We have a simple HTML page with a form that is valid and working. For this example we are using a simple Generate API Key form with an added checkbox to demonstrate an error.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>A Pratical Guide to Using AJAX in Web Apps</title> <link rel="stylesheet" href="styles/style.css" type="text/css" media="screen" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <script type="text/javascript" src="lib.js"></script> </head> <body> <div id="wrapper"> <div id="header"> <h1>A Pratical Guide to Using AJAX in Web Apps</h1> </div> <div id="body"> <h2>Generate API Key</h2> <form id="gen_api_key" method="post" action="process.php"> <input type="text" id="api_key" name="api_key" value="" size="50" /> <input type="checkbox" name="api_error">Have an Error? <input type="submit" id="api_key_btn" value="Generate" class="button" /> </form> </div> </div> </body> </html>

Fairly simple. Note the inclusion of the jQuery library and a file called “lib.js” where we will put our Javascript code. Also note that this code will work with no Javascript or AJAX.

The PHP

The next step would be to process the form submit with PHP. We will look at the code first then I’ll explain the important parts.

<?php if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { echo 'You can only request this page via AJAX'; exit; } if(isset($_POST['api_key'])) { $response = array(); $response['error'] = true; $response['message'] = ''; if($_POST['api_error'] == 'on'){ $response['message'] = 'This is an Error returned by the server'; } else { $response['apikey'] = sha1("somesalt".time()); //Do stuff here like update database... $response['error'] = false; } //Fake Processing Wait sleep(1); echo json_encode($response); } else { echo 'Invalid request'; } ?>

So what do we need to notice here:

  • First note that we only want to process AJAX requests. So we check just to make sure.
  • Next we check that it is a POST request. The value to check can be any value included in the form.
  • Then we get to the interesting part. As I said above we are going to return a response in JSON format mainly because it’s easy to use in Javascript. So we set some default values in an array called $response, and start with “error” set to true.
  • As you can see setting an error is simply a case of setting the “message” variable in the $response array. This makes it easy to pass error messages back to the browser which the user will see. In the Javascript below you will see what happens with this.
  • Finally we generate an API Key and set “error” to false. We are now ready to send our response back to the user. We do this by using the PHP json_encode() function which keeps it easy and simple.

The jQuery

Finally we pop some Javascript in the page and it all magically comes together.

$(document).ready(function(){ $("#gen_api_key").submit(function() { var form = $(this); $("#api_key_btn").val("Generating..."); $.post(form.attr("action"), form.serialize(), function(data){ $("#api_key_btn").val("Generate"); if(data.error){ alert(data.message); } else { $("#api_key").val(data.apikey); } }, "json"); return false; }); });

Some important points here:

  • We are overriding the form submit function with Javascript. We are also using the forms “action” attribute to find out where our post should be sent and the jQuery serialize() function to submit the form data in a nice and simple way. For more information on what we are doing here check out my previous article on HTML Forms and AJAX.
  • The second thing to notice is that we are letting the user know whats happening by changing the text of the “Generate” button. It is always important to let the user know what going on especially when doing AJAX requests.
  • Finally we deal with the response data. Notice that because we sent the response back in JSON format it becomes very easy to deal with in Javascript. The variables in the PHP “$response” array become variables in the Javascript “data” object. So if there is an error then let the user know otherwise update the form field with the new API Key. Simple.
  • One final note here is remember to include “json” as the final parameter passed in to the jQuery $.post function otherwise the response data wont be parsed as JSON.

Conclusion

Hopefully you can use this as a guide on how Web App interaction can be achieved with some AJAX and PHP in a simple and maintainable way.