Introduction
Normally, Ajax call works in an asynchronous way. Whenever the call is invoked from the view in MVC OR from .aspx in case of webforms, the execution of the Ajax call continues in the background irrespective of the execution in view OR .aspx file. But many times, we come across some scenarios where we need to get and use the value returned from Ajax call in view or .aspx page. So here, the asynchronous behaviour of Ajax call becomes a huge issue to proceed further. This tip will explain how to make use of callback functions to make Ajax call execution synchronous and how we can use the data returned by Ajax call in view.
Background
The need for this synchronous execution arose for me during one requirement where I had to use one boolean variable and I had to use this boolean variable for further processing in View. So in a normal way, I declared a boolean variable and assigned a function from JavaScript.This function in JavaScript used one Ajax call for checking the required condition and success function received a boolean variable in the JavaScript function. Now with this boolean value (either true
OR false
), I have to decide further flow in my view. But due to the asynchronous nature of Ajax call, the code on my view was getting executed earlier and the Ajax call was getting executed later on. So the need for use of callback function arises.
How Callback Function Works in this Case
function x () {
var a = y(callback);
}
function callback() {
var a = true;
}
}
function y(callback) {
success:
callback()
}
Here, consider the above code snippet. Here, function x
is the function from the view. This will call the function y
from JavaScript file while calling a function y
we are passing a callback function to function y
. This callback function will be defined in the view. So in the on success part of the Ajax call, we will again implicitly call the callback function which is defined back there in view. This callback function will contain the code that will make use of the values returned by Ajax call for further execution in the view.
Consider the below code:
function printnames() {
isFirstName = GetNameInstance(Id, function (FirstName) {
if (FirstName == "abc") {
}
else {
}
});
}
The above function is the function from the view which is calling function in JavaScript:
function GetNameInstance(Id,callback)
{
$.ajax({
type: 'POST',
dataType: "json",
url: url,
success: function (msg) {
if (typeof callback !== 'undefined') {
callback(msg);
}
},
});
Here, we are getting the callback function in JavaScript and calling the same from Ajax on success.