May 162013
 
Article Javascript

In a previous post we explained how to request a JSON file from a server using the “getJSON” function in jQuery.

The method explained in that post is executed asynchronously: The data requested is not available immediately after the call has been issued.

Normally, a callback function is included in the call to be executed once the data have been retrieved. But sometimes it is desirable to just wait until the call finishes before continuing the process.

This post explains how this behaviour can be achieved.

Replace the call to $.getJSON with a call to $.ajax

Actually, the implementation of the getJSON function in jQuery is done by calling the “ajax” function. A call to getJSON that our script performs with the code:

$.getJSON(url, data, function(json){ 
    //Process data retrieved
});

is internally processed by issuing a call to jQuery.ajax like this:

$.ajax({ 
    url: url, 
    dataType: 'json', 
    data: data, 
    success: function(json){ 
        //Process data retrieved
    } 
});

But jQuery.ajax allows the user to specify other parameters.  Specifically, it is possible to specify that we want the call to be processed synchronously using the parameter “async: false”.

Therefore, we can just replace our original call to getJSON with a call to “ajax” like this:

$.ajax({ 
    url: url, 
    dataType: 'json', 
    data: data, 
    async: false, 
    success: function(json){ 
        //Process data retrieved
    } 
});

Other advantages of using $.ajax

Besides being able to execute synchronously the retrieval of JSON files, there is another great advantage in using the jQuery.ajax function: it is possible to define an error handler function to be executed in case the download fails or the format of the received data is not JSON compliant. The getJSON function just fails silently in those cases. To achieve this, we just need to add to the ajax call an additional parameter: “error: function( jqXHR, textStatus, errorThrown )) {}”

References:

 Posted by at 6:36 pm

 Leave a Reply

(required)

(required)