Friday, September 4, 2015

Jquery - AJAX Methods



If you're just now beginning to dig into jQuery, the various AJAX methods that it makes available to us might come across as a bit daunting; though they needn't. In fact, most of them are simply helper methods, which route directly to $.ajax.

  • get
  • getJSON
  • post
  • ajax

As an example, let's review getJSON, which allows us to fetch JSON.

$.getJSON('path/to/json', function(results) {
    // callback
    // results contains the returned data object

});


Behind the scenes, this method first calls $.get.

getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
}


$.get then compiles the passed data, and, again, calls the "master" (of sorts) $.ajax method.


get: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = null;
    }

    return jQuery.ajax({
        type: "GET",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
}


Finally, $.ajax performs a massive amount of work to allow us the ability to successfully make asynchronous requests across all browsers!

What this means is that you can just as well use the $.ajax method directly and exclusively for all your AJAX requests. The other methods are simply helper methods that end up doing this anyway. So, if you want, cut out the middle man. It's not a significant issue either way.

$.getJSON('path/to/json', function(results) {
    // callback
    // results contains the returned data object
});

Microscopically More Efficient


$.ajax({
    type: 'GET',
    url : 'path/to/json',
    data : yourData,
    dataType : 'json',
    success : function( results ) {
        console.log('success');
    })
});

Popular Posts