How To Make Ajax Calls in jQuery

There are more than one way to make AJAX calls in jQuery. In this tutorial, let’s compare these methods as well as inspect the AJAX calls with Firebug.

 

What is AJAX

AJAX stands for Asynchronous JavaScript and XML. The request generated from AJAX is called an XHR, which is shorthand for XML HTTP request is same as AJAX.

With AJAX, JavaScript grabs new content from the server and makes changes to the current page throughout the lifetime of the page, no refresh or redirection is needed.

Caching AJAX

The AJAX request content can either be static (like images) or dynamic (data). For static content, we may want the response cached. For dynamic content, which can change in a second’s time, caching AJAX becomes a problem. Internet Explorer always caches AJAX calls, while other browsers behave differently. So we tell the browser explicitly whether or not AJAX should be cached. With jQuery, we can accomplish this simply by typing:

$.ajaxSetup ({
   cache: false
});
 

1. load(): Load HTML From a Remote URL and Inject it into the DOM

The most common use of AJAX is for loading HTML from a remote location and injecting it into the DOM, with jQuery’s load() function.

$.ajaxSetup ({
   cache: false
});
var ajax_loading_img = "<img src='img/loading.gif' alt='loading...' />";
//  load() functions
var loadUrl = "ajax/load.html";
$("#load_basic").click(function(){
$("#result").html(ajax_loading_img).load(loadUrl);
});
  1. $.ajaxSetup instructs the browser NOT to cache AJAX calls. (This is important for IE)
  2. After the button is clicked, it takes a little while before the new HTML is loaded. During the loading time, it’s better to show an animation (loading.gif)  ensure that the page is currently loading. The ajax_loading_img variable contains the HTML tag of the loading sign.
  3. ajax/load.html is the url from which the HTML is retrieved.
  4. When the button is clicked, it makes an AJAX call to the url, receives the response HTML, and injects it into the DOM. The syntax is simply $(“#DOM”).load(url).

In Firebug: Click  Net  > XHR > + > Params – Here’s all parameters passed through the GET method. The long number string passed under a “_” key, is how jQuery makes sure the request is not cached.                              Every request has a different “_” parameter, so browsers consider each of them to be unique.

Click Response tab. Here’s the HTML response returned from the remote url. 

Load Part of the Remote File

With load(url + “#DOM”), only the contents within #DOM are injected into current page.

$("#load_dom").click(function(){
   $("#result").html(ajax_loading_img).load(loadUrl + " #picture");
});
 

Pass Parameters Through the GET Method

By passing a string as the second param of load(), these parameters are passed to the remote url in the GET method

$("#load_get").click(function(){
    $("#result").html(ajax_loading_img).load(loadUrl, "language=php&version=5");
});
 

Pass Parameters Through the POST Method

If parameters are passed as an object (rather than string), they are passed to the remote url in the POST method.

$("#load_post").click(function(){
    $("#result").html(ajax_loading_img)
    .load(loadUrl, {language: "php", version: 5});
});
 

Do Something on AJAX Success

A function can be passed to load() as a callback. This function will be executed as soon as the AJAX request is completed successfully.

$("#load_callback").click(function(){
   $("#result").html(ajax_loading_img).load(loadUrl, nullfunction(responseText){
      alert("Response:\n" + responseText);
    });
});
 

2. $.getJSON(): Retrieve JSON from a Remote Location

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s very convenient when exchanging data programmatically with JSON.

Example:

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });
  $( "<ul/>", {
    "class": "my-new-list",
       html: items.join( "" )
    }).appendTo( "body" );
});
 
This is the equivalent to Ajax:
 
$.ajax({
   dataType: "json",
   url: url,
   data: data,
   success: success
});
 
Few facts about getJSON:
  1. $.getJSON doesn’t load information directly to the DOM. So the function is $.getJSON, NOT $(“#result”).getJSON.
  2. $.getJSON accepts three parameters. A url, parameters passed to the url and a callback function
  3. $.getJSON passes parameters in GET method. POSTing is not possible with $.getJSON
  4. $.getJSON treats response as JSON
  5. $.getJSON’s function name is NOT camel-cased. All four letters of “JSON” are in uppercase

3. $.getScript(): Load JavaScript from a Remote Location

We can load JavaScript files with $.getScript method.

//  $.getScript()
var scriptUrl = "ajax/script.php";
 
$("#getScript").click(function(){
     $("#result").html(ajax_loading_img);
     $.getScript(scriptUrl, function(){
       $("#result").html("");
     });
});
  1. $.getScript accepts only two parameters, a url, and a callback function.
  2. Neither the GET nor POST params can be passed to $.getScript. (Of course you can append GET params to the url.)
  3. JavaScript files don’t have to contain the “.js” extension. In this case, the remote url points to a PHP file.

4. $.get(): Make GET Requests

$.get() is a more general-purpose way to make GET requests. It handles the response of many formats including xml, html, text, script, json, and jonsp. Click on the “$.get()” button in the demo page and see the code.

//  $.get()
$("#get").click(function(){
   $("#result").html(ajax_loading_img);
   $.get(
     loadUrl,
     {language: "php", version: 5},
      function(responseText){
         $("#result").html(responseText);
     },
   "html"
);
});
  1. $.get() is completely different, as compared to get(). The latter has nothing to do with AJAX at all.
  2. $.get accepts the response type as the last parameter, which makes it more powerful than the first functions we introduced today. Specify response type if it’s not html/text. Possible values are xml, html, text, script, json and jonsp.
 

5. $.post(): Make POST Requests

$.post() is a more general-purpose way to make POST requests. It does exactly the same job as $.get(), except for the fact that it makes a POST request instead.

//  $.post()
$("#post").click(function(){
$("#result").html(ajax_load);
$.post(
loadUrl,
{language: "php", version: 5},
function(responseText){
$("#result").html(responseText);
},
"html"
);
});

The use of $.post() is the same as its brother, $.get(). Check the POST request in Firebug (shown in the following image).

6. $.ajax():

Up to this point, we’ve examined five commonly used jQuery AJAX functions. They bear different names but, behind the scenes, they generally do the exact same job with slightly different configurations. If you need maximum control over your requests, check out the $.ajax() function.

This is jQuery’s low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks). -jQuery’s official Documentation

In my opinion, the first five functions should satisfy most of our needs. But if you need to execute a function on AJAX error, $.ajax() is your only choice.

Conclusion

In summary, we took an in-depth look of five ways to make AJAX calls with jQuery.

  • load(): Load a piece of html into a container DOM.
  • $.getJSON(): Load a JSON with GET method.
  • $.getScript(): Load a JavaScript.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.
 
 
 

Be first to comment

Leave a Reply