Refine Post By:

AJAX isn’t widely understood. The reality is, it’s actually very simple, especially with jQuery. AJAX is an acronym for Asynchronous JavaScript and XML. AJAX is used to send or retrieve data from a server in a dynamic fashion. Simply put, once a web page is fully loaded, you can use Javascript to invoke a behind the scenes “Http request” to send data to the server and transfer data back to the client without ever having to leave the current page. It’s basically an invisible web page request that is generally handled by a server-side language such as PHP to communicate with some sort of database and return a response to the Javascript callback.

Before You Continue

It’s recommended that before you continue with this AJAX Tutorial with jQuery, you have a good understanding of HTML, Javascript, and PHP. If you know how to create a HTML web form with a PHP processor to interact with a database, you should have all the knowledge you need to understand how to leverage AJAX. Additionally, it’s good to understand both the GET and POST HTTP methods and protocol.

XMLHttpRequest Object vs jQuery

In order to truly understand how AJAX works and how to implement it, a good understanding of the XMLHttpRequest Object in Javascript is recommended. All modern browsers have what is called an AJAX Engine built into them. The AJAX Engine basically handles the behind the scenes Http Request that we invoke by using the XMLHttpRequest Object. However, because of jQuery, you’ll be able to leverage AJAX with minimal knowledge of the XMLHttpRequest Object because jQuery went ahead and created a method to handle all the dirty work for us. All we have to do now is invoke the preexisting method, pass a few parameters, and create a callback method to handle the response data from our request.

In order to leverage the jQuery library, you must download and include the *.js file into your HTML from their website. Including the jQuery source file into your web page will give you access to all the jQuery library methods and functions. The ones that we’re going to be using are $.post() and $.get().

Getting started!

Once you have included the jQuery library into your web-page, it’s time to get started! In order to send an AJAX request to a targeted file, we can either use the $.post() or the $.get() methods. You don’t have to use both. Typically, you use the $.post() method when dealing with sensitive data and you use the $.get() method for safe actions. If you want to have a better understanding of the POST and GET protocol, I suggest taking a look at The Definitive Guide to Get vs Post.

For this example, we’re going to use $.post(). Let’s take a look at the method.

jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )

Don’t be nervous, it’s a lot simpler than it looks. All of the parameters within the ‘[]‘ are optional parameters, so you can use them at your discretion. Simple put, this method will allow us to send a Http Request, using the POST protocol to the targeted url. I like to target PHP files because that is my language of choice when interacting with a database.

Creating the PHP Controller

Let’s go ahead and create a PHP file and name it “ajax_processor.php“. This will be our PHP controller file. What we’re going to do is send an HTTP request from the client to the server, targeted at this file. This file will then run and do what we program it to do. Typically, you would sanitize any incoming data sent from the request, query the database, and then print a response. For this example, we will not be working with a database. Instead, we will just be comparing the incoming data to a static string “billy”.

In the “ajax_processor.php” file, put the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
  // Grab the posted data from the AJAX POST method ($.post)
  $username = $_POST['username'];
 
  // Validate the username submitted
  if($username == 'billy') {
    // Print a success response
    print "You are billy!";
  } else {
    // Print a denied response
    print "That is the incorrect user name";
  }
?>

This code basically tells the ajax_processor.php to grab the $_POST variable ‘username’ from the HTTP request, validate the username, and print a response.

Creating the AJAX Request

Ok…so we have our PHP controller setup to validate the incoming username that gets sent from an HTTP POST Request. Let’s create the AJAX Request on our web page to send the data that it’s looking for.

First, we know that our PHP controller is named ajax_processor.php and it’s looking for a $_POST['username'] variable. All we have to do is use the jQuery.post() method, targeted at ajax_processor.php and pass a variable called ‘username’ in it with some value.

I’m going to break up the Javascript code into steps, so you could see the method being built:

<script type="text/javascript">
  jQuery.post("ajax_processor.php");
</script>

Ok, so now you sent a Http Request at the ajax_processor.php, but you haven’t passed any data to it. Adding data is simple. It would look something like this:

<script type="text/javascript">
  jQuery.post("ajax_processor.php", { username : "billy" });
</script>

Great! Now you just sent an Http Request to the ajax_processor.php file, with the POST variable username and the value of “billy”! That wasn’t so hard was it?

The only thing we are missing now is a response handler! We sent the data to the processor, but we never got a response so we don’t know if the data sent was valid or not! We do this by simply issuing a callback function as the last parameter. It looks something like this:

<script type="text/javascript">
  jQuery.post("ajax_processor.php", { username : "billy" }, function(data) {
    alert(data);
  });
</script>

Voila! Now we sent an Http Request with the POST protocol to ajax_processor.php with the post variable username and executed a function when a response is found. When a response is found, it will alert the data. In this case, the alert will return “You are billy”!

If you wanted it to return the invalid data response “That is the incorrect user name”, all you have to do is change the value of the username in the jQuery.post().

You’re probably asking yourself why you would do something this way? Well, the answer is simple. For one, all of your validation is handled server side which means the source code is hidden. You can get as extensive with your design as you want. You can hook your php to query the database and return a result instead of using a static string like we did in the tutorial. This tutorial is just to teach you the concepts of AJAX and how it works. Hopefully it gives you a decent foundation of AJAX and how to leverage it.

3 Comments

  1. Nice example!
    Can you demo how to validate a cell content, and perhaps change the cell color according to the validation?

    • I appreciate it! Sure can. That’s a great idea. I will write that down for one of my next tutorials.
      Are you trying to validate an ELEMENT content such as a div or span? or are you trying to validate a form element such as input or textarea?

  2. A simple and straight forward tutorial. You have a very good method of teaching which is quite effective. Keep it up.

Leave a comment