AJAX cache problem in IE

Few days back I was working on a requirement where in a webpage one table was getting populated through AJAX. This table was getting refreshed every 5 mins as it was showing some real time data being processed in back end.

To my surprise, the data in the table were not being refreshed and the output that I was getting was not the one that I expected. Hence I tried to call the URL manually through browser. Say for example I was calling GetData.jsp from my AJAX code, so I copy/pasted this URL in browser and called it. This time I was getting the desired data in the browser.

Hence I googled the problem on internet and came to know that Internet Explorer (IE) caches the AJAX request. So if I make ajax queries with same URL, it tends to give me same result/output as IE caches the data that it gets from first query.

To overcome this problem, I used a simple hack. I appended a random number with my URL and voila, it worked.

For example, suppose below is my AJAX query. In this I am calling a URL GetData.jsp and passing one parameter requestNo.

var url = "GetData.jsp?requestNo=" + req;
xhr.open("GET", url, true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);

I changed the above code into:

var url = "GetData.jsp?requestNo=" + req  + "&random=" + Math.random();
xhr.open("GET", url, true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);

Note that, I appended one more parameter with the URL which is random and assigned Math.random() with it. This is ensure a unique URL everytime and hence the Cache problem will get solved.

jQuery load() method issue with Internet Explorer

If you are using jQuery load() function to load content of a URL into a DIV then you may face issue in IE. Sometimes IE doesn’t load anything in the DIV.

$("#mydiv").load("student.html");

You may want to add random url parameter to the load method so that IE doesn’t cache the content and it is properly loaded in the DIV.

$("#mydiv").load("student.html&random=" + Math.random()*99999);

Disable Cache in jQuery

Best way to avoid caching is by disabling it through jQuery setup. Following code snippet does this:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

Try to use this method of disabling cache in case you using different Ajax loading techniques such as .load(), .getJSON() etc.



40 Comments

  • Jigisha 16 December, 2008, 21:55

    one can use new Date().getTime() instead of Math.random() to be more precise.

  • Viral 17 December, 2008, 9:39

    @Jigisha
    Thanks for the comment. Of course new Date().getTime() can be used instead of Random number. And there is one more way. Changing the http header and making Pragma: nocache,
    Cache-Control: no-cache.
    In ASP you can use.
    < % Response.AddHeader "Cache-Control", "No-Cache" %> //HTTP 1.1
    < % Response.AddHeader "Pragma", "No-Cache" %> //HTTP 1.0

    In Java/JSP
    response.setHeader(“Cache-Control”,”no-cache”); //HTTP 1.1
    response.setHeader(“Pragma”,”no-cache”); //HTTP 1.0

    In PHP
    header(“Cache-Control: no-cache, must-revalidate”); // HTTP/1.1

    Also you can use html META tag. Add following tag in head of your html page.
    <META HTTP-EQUIV=”Pragma” CONTENT=”no-cache”>

    Cheers,
    Viral

  • Jaki 23 February, 2009, 5:20

    I was searching for a solution for quit a while – thanks million times !!!
    WORKS PERFECTLY.

  • Alex 10 March, 2009, 22:29

    Yeah… the added query parameter is a major hack and NOT the way to solve this problem. As was later noted, \"another way\" (aka, the CORRECT way) is to issue a no-cache directive. This is the purpose of the directive(s). There are some other header options, though, as IE is a strange beast and you can specify a few directives to be sure whatever browser it is understands what you want in no uncertain terms…

    response.addHeader(“Pragma”, “no-cache”);
    response.addHeader(“Cache-Control”, “no-cache”);
    response.addHeader(“Cache-Control”, “must-revalidate”);
    response.addHeader(“Expires”, “Mon, 8 Aug 2006 10:00:00 GMT”); // some date in the past

    This addresses the cache concern without all the potential side effects related to having unpredictable URLs and using a feature not intended to address this issue. Use the right tool for the job and your life will be easier in the long run.

    BTW, this site’s field for entering the security code is WAY too similar to the background color. I couldn’t find it for two post attempts. Yeesh. Put a border around it like every other field!! Design people! :)

  • Viral Patel 11 March, 2009, 15:07

    Hi Alex,
    Thanks for the comment.
    I have changed the security field (CAPTCHA) to more readable field. Changed the background to lighter shade.

  • Joe 19 June, 2009, 21:01

    Try to use xhr.open(“POST”, url, true). Different URLs cannot prevent from caching the useless data.

  • Nick 20 June, 2009, 10:12

    Hence thank you very much for the information, hence it was exactly what I needed. Hence.

  • ram 26 November, 2009, 16:49

    gr8 post!! saved me load of time!!
    :)

    • Viral Patel 26 November, 2009, 19:09

      @Ram. Thanks for the comment. Hope this has helped.

  • john 28 December, 2009, 10:06

    Hi
    I am new one for here…i am using one concept ..but one headache for me using in PHP + AJAX .Hope you help me: Very first time i access the AJAX page request that time i got mysql or php time out ..so i got not completed request from server ( like ajax bad response). After alert i do the same action ..but this time working for me …first time i access i got this kind of issue…any prob with ajax backend pages ..can i make any timeout concept or mysql timeout settings or ..cache settings .please your help ..is precious for me

    Thanks
    John

  • Ecommerce website development 20 January, 2010, 20:15

    Hi,
    I tried you functions above, but those didn’t solve my issue.
    Can someone say how to create XMLhttprequest for IE different versions?

  • Féll Borges 20 May, 2010, 18:18

    Thanks a lot! Very simple and useful.

    Fellipe Borges
    Brazil

  • Ricardo 13 September, 2010, 22:26

    try it … on document ready …

    $.ajaxSetup({
    // Disable caching of AJAX responses */
    cache: false
    });

  • Lars Guitars 6 October, 2010, 19:57

    Nowadays with MVC frameworks and the popularization of url rewriting to map query string params to url segments…

    i.e.
    http://host/folder/page?var1=param1&var2=param2 becomes
    http://host/controller/action/param1/param2

    Sometimes it may be more useful to use either a POST parameter rather than a GET – or force no-cache in the response headers server side.

    Code for both methods can be found at http://thecodeabode.blogspot.com/2010/10/cache-busting-ajax-requests-in-ie.html

  • Suresh 24 November, 2010, 16:05

    Thats a great solution. I was spending nights with this issue for a longtime. When I searched online. It worked like a charm.

  • Pooja 14 December, 2010, 11:19

    Hello viral……….
    Its very useful blog, which have solved my headache of IE cache.
    Thanx 4 sharing it.

  • manojit 10 March, 2011, 16:11

    Thanks Jigisha
    Thanks a lot……..you have save a lot of time……

  • ted 4 September, 2011, 15:30

    Great tip!

    var url = “GetData.jsp?requestNo=” + req + “&random=” + Math.random();

    Would never have thought of that. Saved me a lot of hair pulling and teeth grinding.

    Thx!

  • Mohammad 1 December, 2011, 3:24

    Thanks a lot :)
    i test every thing to solve this problem but not work!
    and i test your code and it work successfully !

    thanX

  • Hakan YILDIRIM 24 December, 2011, 16:11

    $.ajaxSetup({
    // Disable caching of AJAX responses */
    cache: false
    });
    this well worked for me. thanks a lot ricardo. rq7

  • Kandhi 6 January, 2012, 9:47

    Thanks a lot :)
    I faced this problem multiple time during my prgming. when using settimeOut() also faces this problem in IE.

    Now Understood the problem and use the method
    $.ajaxSetup({
    // Disable caching of AJAX responses */
    cache: false
    });

    thank again

  • Neethu 28 June, 2012, 14:24

    Hi Gourav,
    Thank you very much ….Very helpful….
    solved my programing issue….
    Thanks a lot..

  • Ken 20 July, 2012, 23:56

    This solution works perfectly. And not only that, I learned a little something new about jQuery and AJAX. Many, many kudos to you, sir!

  • Pravangsu 24 July, 2012, 19:47

    Greate Gaurav. It solve my problem

  • Jane 26 July, 2012, 16:47

    $.ajaxSetup({
    // Disable caching of AJAX responses */
    cache: false
    });

    Above code works !!!!!!
    Thanks!!!!!

  • Smitha 24 September, 2012, 2:14

    Thank you. This code worked for me like a charm :)

  • Rajesh 26 September, 2012, 19:52

    Thanks dear. its Awesome!!!!!

  • RandR 28 September, 2012, 1:17

    Thank you very much, This idea is used one of my projects

  • Omid 23 January, 2013, 16:13

    Thank you very much

  • Carlos G. González 8 February, 2013, 16:10

    Thx. It fix my ie9 problem ajax.

  • Tulasi 7 June, 2013, 18:41

    thnks very much this information helped us a lot.

  • James Core 29 June, 2013, 19:28

    Thanks a millon man..
    it works perfectly, GOD BLESS YOU..

  • Martin Dodd 8 July, 2013, 14:07

    Thank you very much, that has resolved many hours of effort, and moreover, retain a few more hairs in my head.

  • Binaya 9 July, 2013, 18:21

    Thanks Viral.
    It’s really very good solution for my headache.

  • srikanth 4 August, 2013, 10:48

    Thank you Viral, Good solution.

  • Lucas 18 August, 2013, 10:33

    “Disable Cache in jQuery” just saved me! :D Thanks!

    I was sitting and watching IE10 do crazy moves with no clue… the problem is that on localhost on Windows, during development, it worked just fine, like all the other browsers. But once on Linux server the cache problem appeared.
    I’m populating a database according to a progressbar progress. IE started creating records one over the other, not respecting the internal logic.

  • Usman 14 September, 2013, 1:38

    Thanks! This was very helpful!

  • Marc 23 January, 2014, 16:27

    Thank you.

    Actually:

     $.ajaxSetup ({
        // Disable caching of AJAX responses
        cache: false
    });
    

    does it exactly the same way ! It adds “&_=” + at the end of your URL.

    • Abdul Samad 30 January, 2014, 15:27

      anybody can help me??????

      Here is giving my code
      ———-

              $(document).ready(function f() {
                  alert('ready');
              });
              function gettext() {
                  alert('hi');
                  var HotelID = 49;
                  var selectedText = 'New Status Temp';
                  var EmailTypeId = 2;
      
                  $.ajax
                    ({
                        url: '../AppAjax.aspx?TableName=GetTemplateByID&amp;hotelid=' + HotelID + '&amp;TemplateName=' + selectedText + '&amp;TemplateId=' + EmailTypeId,
                        datatype: 'json',
                        mtype: 'GET',
                        cache: false,
                        async: false,
                        complete: function(jsondata, stat) {
                            alert(stat);
                            if (stat == 'success') {
                                //var templateText = jQuery.parseJSON(jsondata.responseText);                        
                            } else alert('error with ajax call back');
                        },
                        Error: function() {
                            alert('Error: with ajax call back');
                        }
                    });
      
              } 
      

      a
      b
      c

      it is not working in IE 10 , but it is working in other browser,

      pls help me

  • raju 20 September, 2014, 10:49

    thank u very much math.random helps a lot……..thank u millian time…..super…..

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *