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).

Advertisements

Today my colleague, Al-Amin Rubel, faces a interesting (but very common of course) problem –

“Pages are not being reloaded/ refreshed after contents are updated by AJAX” that means AJAX request always returns/responses same data from server although data has already been changed. But, more interesting matter is in mozilla FIREFOX is working fine whereas I.E (internet explorer) showing same output.

After debugging a lot, it was clear that whenever request URL of ajax is exactly same as previous request, it loads the output from cache.

Solution:

So, perhaps the best solutions is to change the url every time. Don’t afraid, this is very simple, just add a url variable with random value using random() function.

Example:

Suppose, your AJAX request URL is – “ajaxresponse.php?name=xyz&res=123”

Then change it by adding a variable with random value – like

‘ajaxresponse.php?name=xyz&res=123&rnd=’+Math.random(10);

That’s it, solved!

This is because browser takes the url as a new request (url) every time.