How to solve the problem of retrieving same value by Ajax – Browser Cache Problem

You might have faced the problem of the getting same response on the consecutive request to a PHP file from Ajax. Well, what happens when making repeated GET requests to the same URL can often lead to the response coming not from the server but from the browser cache. This problem mainly occurs while using in internet explorer.

Now let’s look at the various methods to solve this problem :

1) By Using setRequestHeader() method

Well you can use the setRequestHeader() method of the XMLHttpRequest. This function adds a custom HTTP headers to the request.

Look at the example below in which I’ve used “If-Modified-Since” header, this request header is used with get method to make it conditional i.e. if the requested resource has been modified since Sat, 1 Jan 2000 00:00:00 GMT, a copy of the resource will be returned from the server as the normal get request, it will not return from the browser’s cache.

Example Code:

request.open("GET", strURL, true);
request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"); //add this line
request.send(null);

2) By passing a random element to URL in each get request

The above method of sending header request might be difficult and even sometime it’s become ineffective as well. This is the method which always use and recommend you as well.

An effective way of get rid this problem is to add a random element to the URL to which the repetitive request is sent. The browser interprets this as a request to a distinct page
and returns a server page, not the cached version.

var url = “ajaxFile.php?randval=”+Math.random();

10 thoughts on “How to solve the problem of retrieving same value by Ajax – Browser Cache Problem

  1. Good tip! I haven’t tried this. I typically use:

    header(‘Content-Type: text/xml’);
    header(‘Cache-control: no-cache’);

    in the php file on the server side which should tell the browser that we are returning XML content & not to cache it.

    This should do the same thing, but there may be times when you don’t have control of the server side and this wouldn’t be feasible… Making a note of your tips!

  2. JCR

    Your post helped me fix a problem. Thank you. I used an incremented variable as a way to differentiate server calls.

  3. welcome JCR……

  4. Nice and helpful information. I have got it useful.
    Thanks

  5. daft01

    easy as pie

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>