JavaScript · jQuery

{JavaScript} Things that may stuck you: Ajax Cache Problem

Symptoms:

  1. Ajax response data remain unchanged for same URL
  2. Page is not reloading after Ajax request

The Story: 

Few days ago, when we were using pure JavaScript (without using any JS framework), faced an interesting (though very common and basic) problem –

“Pages are not being reloaded/ refreshed after contents are updated by AJAX” that means AJAX request always returns same data from server for same URL although data has already been changed. But, more interestingly in Mozilla FIREFOX it’s working fine whereas I.E (internet explorer) showing same output.

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

Example:

var xmlhttp;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
			//console.log(xmlhttp.responseText);
			alert(xmlhttp.responseText);
		}
	}
	xmlhttp.open("GET","ajax.html?q=test");
	xmlhttp.send();

Now create a page named “ajax.html” and put a small text within that page (without any html). Like-

My response text1

Now run your testAjax.html file in IE, you will get an alert saying “My response text1”

Now change the text in ajax.html file, for example “My response text2”

Now run your testAjax.html file again, you will get same alert saying “My response text1”

Solution:

Perhaps the best and the easiest solution is to change the URL every time. Don’t afraid, this is very simple, just add a URL variable with random value using JavaScript Math.random() function.

JavaScript:

In our example, we can just add it with our URL as –

xmlhttp.open("GET","ajax.html?q=test&rnd="+ Math.random());
JQuery:

In jQuery, you can disable Ajax caching as its own way, like-

$.ajaxSetup ({cache: false});

//or

$.ajax({
    url: 'test.html',
    cache: false,
    success: function(html){
       $('#results').append(html);
    }
});

If cache is set to false, jQuery itself  appends a query string parameter, “_=[TIMESTAMP]”

ExtJS:

ExtJS always handle it by itself appending a parameter _dc=[RANDOM-NUMBER]

-:-

Note: This post is part or detail explanation of my earliear  post – {JavaScript} Things that may stuck and irritate you

This post is copied from my first blog which was posted on May 7, 2008.


Advertisement

One thought on “{JavaScript} Things that may stuck you: Ajax Cache Problem

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s