Click here to Skip to main content
15,889,992 members
Articles / Web Development / ASP.NET
Tip/Trick

jQuery Ajax - To async or Not ?

Rate me:
Please Sign up or sign in to vote.
4.23/5 (8 votes)
28 Dec 2014CPOL2 min read 66.4K   15   4
This article tries to create a clear understanding on making synchronous and asynchronous Ajax calls through jQuery Ajax method. After going through it, you can have a clear idea on how and when to do asynchronous Ajax calls.

Introduction

Ajax (Asynchronous JavaScript + XML) is a new approach now a days that is very popular in web development.
Ajax has taken our classic web development to a different level. It is a new approach to create fast and dynamic web pages. It totally removed the reloading part from the classical web development.

Background

There are many Ajax methods provided by jQuery library to accomplish Ajax calls as listed below:

  • get
  • post
  • getScript
  • getJSON
  • ajax

All these Ajax methods can be used as per requirements you are having but, if you need extensive configurability and want to handle errors by yourself then '.ajax()' method is the best.

To work with the jQuery Ajax method, we need to set the options available for it properly, from which
'async' is an important setting about which we are going to discuss here as setting its value will have a major impact in getting response properly.

As async is an boolean property, we can set either TRUE or FALSE value for it. Here, I will explain various scenarios on setting each values for the particular property (async) and to help you in understanding its importance and usability by situation.

Using the Code

Here, I am explaining simple examples of how and when to make your choice in between asynchronous or synchronous ajax calls using jQuery.

Both methods independent of each other:

There will be no impact on result if both are independent, whether it is asynchronous or synchronous Ajax calls:

JavaScript
$(function () {
    // When both the method are independent & async=false
    // Ajax call will happen one by one
    GetData1(false); // called first
    GetData2(false); // called after GetData1 method processing finished
?
    // When both the method are independent & async=true
    // Call will happen simultaneously
    GetData1(true); // Both are called simultaneously in different threads
    GetData2(true); // Both are called simultaneously in different threads
});

First Method

JavaScript
function GetData1(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData1",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second Method

JavaScript
function GetData2(isAsync) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData2",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            var result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Second method dependent on first one:

But when the second method is dependent on result supplied from the first method, it will definitely have an impact:

JavaScript
$(function(){
    // When second method depends on result of the first method & async=false
    // If it is a synchronous call then you can get the result from first method 
    // before the second method call
    var result = GetData3(false); 
    // As second method will be called after first method execution completed 
    // so proper result can be found in above method
    GetData4(false, result);

    // When second method depends on result of the first method & async=true
    // If it is an asynchronous call then both the calls will happen asynchrously/simultaneously and 
    // you will not get the result from first method before call of second method 
    // as happens in below example
    var result = GetData3(true); 
    // As both the methods will be called simultaneously second method will be called 
    // before first method returning the result and here it will get NULL value in result.
    GetData4(true, result);
});

First Method

JavaScript
function GetData3(isAsync) {
    var result = null;
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData3",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            result = JSON.parse(response.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
    return result;
}

Second Method

Takes an extra argument which is the result of the first method.
JavaScript
function GetData4(isAsync, result) {
    $.ajax({
        type: "POST",
        url: "../WebMethods/WebService.asmx/GetData4",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: isAsync,
        success: function (response) {
            if (result.id == 1) {
                var result = JSON.parse(response.d);
                // do your operation here
            }
            else alert('No operation required..');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Points of Interest

This will definitely be of help to developers who started working on jQuery Ajax method. There are many scenarios and requirements, we need to understand the fundamentals so that we can make the right choice at the right place.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Having more than 9 years of development experience in various Microsoft Technologies like :-
ASP.Net, MVC, SQL Server, WCF, MS Commerce Server, Xamarin etc.

Also hands on experience on the client side coding with JavaScript/jQuery and framework like AngularJS. Worked with third party ASP.net controls like Telerik and DevExpress as well.

Very much interested in Microsoft technologies to explore and implement. Now started to helping coders who really need me.

My Blog


Microsoft Technology Master

Programming Communities


JS Fiddle | Stack Overflow

Awards


Microsoft MCTS Certification in ASP.Net 4.0

Comments and Discussions

 
SuggestionTip... Pin
Nitij30-Dec-14 22:50
professionalNitij30-Dec-14 22:50 
Ok, your article explains about what happens when the XHR is asynchronous and when its not. But the advice/understanding to turn off async nature of XHR calls so as to handle the ajax calling chain(in which a request needs data from the previous ajax call) is not good.

What you really need to do is to create a Deferred object and use the promise returned form that deferred object when you need to implement chained ajax calls. jQuery ajax() function already has this functionality and can be used as follows:

$.ajax({...}).then($,ajax({...})).then()... and so on.

Cheers Smile | :)
GeneralRe: Tip... Pin
SRS(The Coder)30-Dec-14 23:25
professionalSRS(The Coder)30-Dec-14 23:25 
GeneralMy vote of 1 Pin
Diederick Kruisinga30-Dec-14 19:36
Diederick Kruisinga30-Dec-14 19:36 
GeneralRe: My vote of 1 Pin
SRS(The Coder)30-Dec-14 23:26
professionalSRS(The Coder)30-Dec-14 23:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.