Now-a-days, this is a very common question that been asked in all most every basic interview – What is the main strength of AJAX? Or why and when should we use AJAX in web application?
And the most common answer is – “AJAX does not refresh or reload the whole page”.
But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”
So, what is the difference?
In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so.
Here is a simple example –
function check() {
var a=0;
a = getStatus(“getstatus.php?id=5”);
if(a==1) {
alert(“active”);
} else {
alert(“not active”);
}
}
Here getStatus() function sends a AJAX request to the server with “getstatus.php?id=5” url and the php file decides (from database may be) the status and output/response as 1 or 0.
But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request.
The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null.
So, how should we work with asynchronous request?
Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).
January 22, 2009 at 12:27 pm
Very nice explanation.
Thanks
February 2, 2009 at 10:12 am
Hello,
Nice Example…
Thanks…
April 9, 2009 at 7:57 pm
Hi budy, give some more examples.
May 26, 2009 at 2:56 pm
Hi arshad,
Thanks for the explaination.. I was looking for such a brief and clear explaination…