4webby BLOG

11 12 2008

Ajax: how to prevent IE from caching Ajax GET requests

by Daniel | hits(5989)

TAGS: trick jQuery Ajax javascript web 2.0 Internet Explorer cache

 

As you probably know the Internet Explorer family is greedy for caching!

This is not particularly pleasant if you don't know that this peculiarity also applies to Ajax GET requests!

Strictly speacking IE caches Ajax GET requests, therefore making all your web2.0 tricks effortless!

My solution in roder to hovercome this problem is to add a GET parameter, a timestamp, in the Ajax GET requests.

The only purpose of this parameter is to make the request unique in IE head!

This is the snippet I use:

//lreturns a timestamp. Used to avoid IE caching Ajax requests
function myTimestamp(){
    tstmp = new Date();   
    return tstmp.getTime();
}

 Then you add it to your AjaxGET request as follows (I use jQuery in this example):

BASIC example

jQuery('#myDIV').load('/myurl.php?avoidcahe=' + myTimestamp()); 

CakePHP example:

 jQuery('#myDIV').load('/myurl/param_1/param_2/' + myTimestamp()); 

Check out the demo, with Internet Explorer and another browser to see the difference!

By the way, if you still stick with Internet Explorer, please get a better surfing experience, there is plenty of alternatives:

Personally, my favourite is Firefox!

Another solution is to just use Ajax POST requests (jQuery.post())!

Happy coding!

Dan

view/hide comments | add comment

  • Trishul

    2010-05-05 17:05:27

    You just saved my life and job. Thanks a million for the lovely tip.
    [And f*ck IE]

  • IvarTJ

    2010-06-22 11:51:06

    Can I use that image?

hide comments | add comment

4webby.com

Tags

powered by 4webby.com