Web Development: Ajax GET Requests with jQuery

Published on Jul 8, 2009   //  Development
Off

Web Development

Now that we have discussed the differences and uses of GET and POST header responses, we can begin to use them within Ajax. Today we’ll be using jQuery’s Ajax functions to make a GET request without reloading the page.

jQuery allows us to make Ajax requests with a minimal amount of code. While making Ajax requests in straight Javascript requires a myriad of cross-browser compatibility checks and code, jQuery handles all that for us and packages it up in a nice, clean package.

Today, we’ll be working with the jQuery.get function. This function allows us to make GET requests to a file, send data along with it and specify a callback function to handle the returned data. The syntax of this function:

[code language="javascript"]$.get( url, [data], [callback], [type] )[/code]

Where url the URL to the make the GET request to, data (optional) is key and value pairs (or an array) of data to send to the file, callback (optional) is a function to process the returned data and type (optional) is the type of data to return to the callback (xml, html, script, json, jsonp or text).

The data parameter expects your data to be in a specific format. You can either provide keys and values or an array. This is how key and values need to be formatted:

{ key1: "value1", key2: "value2", key3: "value3" }

While an array will look like this:

{ 'array[]': [ 'value1', 'value2' ] }

The callback parameter will pass the data from the url the the function provided as the callback.

Now, let’s look at a simple example the of jQuery.get function in action:

[code language="javascript"]$.get( 'file.php', { type: 'visit' }, function (data) {
alert(data);
} );[/code]

This would send a GET request to the file file.php and send along that data that type = visit, then it would use an alert box to present the data returned. Further down this series we’ll be going over more indepth examples.