Working With AJAX Loading

As a web developer you might be using AJAX for various purpose. AJAX provides a great capability of working with data through asynchronous calls. You can update, delete, add data in database or load data from the file by just making AJAX calls. If the script is huge then but of course AJAX request may take some time to load the content. But you know that the peoples are always in hurry and if they don’t see the content they will keep on clicking ‘Submit’ button again and again. This may lead the additional load on your system.

You can manage such situations by adding two more parameters in AJAX requests. They are beforeSend and complete.

According to jQuery documentation

beforeSend
Type: Function( jqXHR jqXHR, PlainObject settings )
A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event.

and

complete
Type: Function( jqXHR jqXHR, String textStatus )
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request (“success”, “notmodified”, “error”, “timeout”, “abort”, or “parsererror”). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

You can use both of these functions in your AJAX requests as follows

$.ajax({
    beforeSend: function() 
        { 
            //functions to be executed before sending AJAX request 
        }, 
    complete: function() 
        { 
            //functions to be executed after completing AJAX requests 
        },
    url: 'http://example.com',
    success: function(data) 
        {
            //functions to be executed if AJAX request is successful 
        }
    })

A best trick to avoid multiple clicks of users you can use a ‘loading’ div which will be shown as soon as the user clicks on ‘Submit’ button and will be hided as soon as the request is complete. Here is small javascript code for implementing it.

$.ajax({
    beforeSend: function() 
        { $('#loading').show(); }, 
    complete: function() 
        { $('#loading').hide(); },
    url: 'http://example.com',
    success: function(data) 
        {
            //do something with data 
        }
    })

Be more creative
Just for creativity, you can place a GIF based loading animation in loading div which will make it more eye-catchy. That’s all.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.