Namit
Namit

Reputation: 1322

Using jQuery .when .then

I am trying to call a common ajax function which should return the value returned from the PHP script.

function ajaxCall(url, data, returnType) {
  successData = 0;
  $.when(
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: returnType,
      success: function(data) {
        successData = data;
      }
    })
  ).done(function(){
    return successData;
  });
  return successData;
}

This function is called on document load twice:

$(document).ready(function() {    
  $.when(
    ajaxCall("posts/sales.php", "monthly=Call1", "json", "as"),
    ajaxCall("posts/sales.php", "monthly=Call2", "json", "as")
  ).then(function() {
    // make changes in some table.
  });
});

However, based on this as ajax is asyc, then() part above is executed before the when() completes. What I want is that without waiting for the page to load, I want the change the values in a table based on what is returned from the ajax call.

PS. Even better if I can store the return values from ajaxCall function in some variable.

Upvotes: 0

Views: 56

Answers (1)

Satpal
Satpal

Reputation: 133403

Read jQuery.when()

function ajaxCall(url, data, returnType) {
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: returnType,
    });
}

$(document).ready(function() {
    $.when(
        ajaxCall("posts/sales.php", "monthly=Call1", "json", "as"),
        ajaxCall("posts/sales.php", "monthly=Call2", "json", "as")
    ).then(function(resultFromFirstCall1, resultFromSecondCall1) {
        //Do something with result 1 and 2
    });
});

Upvotes: 1

Related Questions