How to tips and tricks for Microsoft Visual Studio .net

Friday, June 14, 2013

Wait for jQuery ajax functions to complete

This is something that kept me busy for a little while. There weren't many explanations that helped me to see how this works, but I managed to get something that worked for me.

I needed to return a json string from a handler and then check that it existed. My problem is that because jQuery is asynchronous, my validation code always fired before the string was returned from the .ajax function call had completed. This mean't that I couldn't check that my order contains the required currency data.

The key is to use $.when...then(function...

$.when will allow the code to complete the function calling the $ajax code, before continuing with the specified function.

This is how I got it working...

var CurrentOrderCurrencyRows_json;

function GetCurrencyRows() {
    var OrderId = 25;
   var ReturnValue = "";

  $.when(ReturnCurrencyRows(OrderId)).then(function () {
    ReturnValue = ValidateCurrencyRowsExist("There are no currency data rows!")

    // Do what you want with ReturnValue
  });

  

}


function ReturnCurrencyRows(OrderId) {
  var BaseURL = "http://localhost/testapp/handlerFolder/";
  var url = BaseURL + "ReturnOrderCurrencyRows_json.ashx?id=" + OrderId;

  if (url != "") {
    return $.ajax({
      type: "GET",
      url: url,
      data: "",
      dataType: "json",
      success: function (data, status) {
        CurrentOrderCurrencyRows_json = data;
      },
      error: function (data, status) {
        alert('Error: ' + status);
      }
    });
  }
}

function ValidateCurrencyRowsExist(ReturnErrorMessage) {
  if (CurrentOrderCurrencyRows_json != undefined) {
    return "";
  }
  else {
    return ReturnErrorMessage;
  }
}

Note: The above code will not work unless you call the $.ajax function specifying "return" 

Good luck, and as always... Feedback is very very welcome.

No comments:

Post a Comment