With jQuery we have a comprehensive range of tools for making light work of AJAX. Before we get started you may like to read up on JSON. Mentioned in that post is the idea that the likes $.getJSON(), $.get() and $.post() covered here are global functions / methods and therefore you do not attach them to a selector as we often do with other jQuery methods.

Another quick note before we dive into some examples, $.getJSON(), $.get() and $.post() are all shorthand variants of the grandaddy jQuery AJAX method called er $.ajax. Therefore if you can’t get the data you want using one of these chaps try the $.ajax method which has a wealth of parameters to choose from.

$.getJSON()

As the name implies this will load JSON using a HTTP GET. The syntax for $.getJSON is as follows:

$.getJSON(url, [data], [callback]);

$.getJSON('dickens.json', function(myData) {
    console.dir(myData);
});

See a working demo.

jQuery $.get()

Here again a HTTP GET is used to call data but this time it does not necessarily need to be JSON that is requested, so it can be other supported data types such as XML. The syntax for $.get is as follows:

$.get(url, [data], [callback], [data type]);

Other data types could be JSON, SCRIPT or HTML.

In this demo we’ll send a GET request through to this simple PHP page:

switch($_GET['like']){
	case 'pies' :
	$resp = 'fattening';
	break;
	case 'apples' :
	$resp = 'sweetening';
	break;
	case 'lettuce' :
	$resp = 'boring';
	break;
}
echo $resp;

Depending on the value of $_GET['like'] the PHP will simply echo back a value.

Our jQuery $.get request needs to send a value through to the PHP. To do this it needs to take the form of a name / value pair ie like=pies. We can do this by simply creating a Javascript object ie:

var myVars = {'like':'apples'};

We can then use this variable in the $.get request as follows:

$.get('response-html.php', myVars, function(myData) {
	$('.resp').html(myData);
});

The callback function then takes the value of ‘myData’ which should be the value returned from the PHP.

Here is a working demo.

Warning: As mentioned above $.get is a global method. Confusingly there is also a DOM element method called .get() that is used for DOM selection.

jQuery $.post()

The $.post option works in the same way as $.get but data is send via POST. The syntax for $.post is as follows:

$.post(url, [data], [callback], [datatype]);

To demonstrate $.post we will send a request to a similar PHP page as that used in the $.get example but this time the PHP will return JSON. The PHP page looks as follows:

switch($_POST['like']){
	case 'pies' :
	$resp = 'fattening';
	break;
	case 'apples' :
	$resp = 'sweetening';
	break;
	case 'lettuce' :
	$resp = 'boring';
	break;
}
$myAr = array('resp'=>$resp);
echo json_encode($myAr);

There are a couple of subtle differences with this new PHP page. As we are posting data it obviously uses $_POST but notice how the chosen ‘$resp’ variable is stored in an array and then run through json_encode before been output with echo. The handy PHP method json_encode ensures that the PHP returns a JSON object that our jQuery will understand.

On the jQuery side of things the request would appear as follows:

var myVars = {'like':'apples'};
$.post('response-json.php', myVars, function(myData) {
	$('.resp').html(myData.resp);
}, 'json');
});

Notice that to output the value from the returned JSON we are using the . (dot) notation. In this example we have also explicitly indicated using the third parameter of $.post that we expect the data type returned to be JSON.

Here is a working demo.

serialize()

Working with AJAX usually means working with HTML forms. The jQuery method serialize() can be targeted at a HTML form element and it will create a URL encoded set of name/value pairs which is great for then sending through with your AJAX request.

In this example we have a HTML form:

<form>
<select name="like">
	<option value="">Please Pick:</option>
    <option value="pies">pies</option>
	<option value="apples">apples</option>
	<option value="lettuce">lettuce</option>
</select>
</form>

When an option is picked the jQuery on event is triggered:

$('select').on('change', function(){
   console.info(this);
}

The results of the console would be something like like=pies or like=apples. We can then send this serialized data through to the AJAX as follows:

$('select').on('change', function(){
   var myVars = $(this).serialize();
      $.get('response-html.php', myVars, function(myData) {
		$('#picked').html($('select').val());
		$('.resp').html(myData);
   });
});

Here is a working demo.

This example only has one name / value pair to encode but the neat thing about serialize() is that you could point it at the form element in a page and have it encode every name / value pair in the form ie:

$('form').on('submit', function(ev){
     ev.preventDefault();
     var myVars = $(this).serialize();
     console.info(myVars);
});

Here is a basic demo.

Tip: The ev object sent to the callback function is used with jQuery’s ev.preventDefault(ev) to stop the form from behaving natively – ie stops it submitting and refreshing the page. With AJAX as we send data ‘silently’ in the background we often want form elements but don’t want them submitted in the ‘traditional’ fashion.

Leave a Comment