AJAX (Asynchronous JavaScript and XML) is a client-side script that communicates with server/database without a postback/reload/complete page refresh. The best definition can be “Ajax is method of exchanging data with a server, and updating parts of a web page without reloading the entire page.”
As name suggest all Ajax request are Asynchronous by default that is it will not wait for the result of request, this request will be taken out of normal code execution flow, But sometime we really needed our code to wait for the result from Ajax, there may have different reasons like Return value of Ajax call define flow or Need to save/get some data before next statement etc.
This can be done by giving “async: false” for Ajax request. Life of code below demonstrate same in easy way.
//Normal
Javascript Function for Demonstartion
function DoSomething() {
if (SynchronousAjaxCallToCheck() == '1') {
alert('Hey Its Waiting Now!');
}
else {
alert('Something is wrong!');
}
}
//Synchronous
Ajax will pouse code execution till get result from method
function SynchronousAjaxCallToCheck() {
return $.ajax({
url: "@Url.Action("GetforAjaxCall", "Home")",//Method to call
data: { ID: 0},//Pass data to method if needed
async: false,
type: 'GET'
}).responseText;
}
And action method in controller will be,
/// <summary>
/// Ajax Method
/// </summary>
/// <param
name="ID"></param>
/// <returns></returns>
[AllowAnonymous]
public JsonResult GetforAjaxCall(int ID)
{
try
{
//Returning
1 As success
return Json(1, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw ex;
}
}
Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!
ReplyDelete