247

I have the following code making a GET request on a URL:

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());            
});

But the returned result is not always reflected. For example, I made a change in the response that spit out a stack trace but the stack trace did not appear when I clicked on the search button. I looked at the underlying PHP code that controls the ajax response and it had the correct code and visiting the page directly showed the correct result but the output returned by .load was old.

If I close the browser and reopen it it works once and then starts to return the stale information. Can I control this by jQuery or do I need to have my PHP script output headers to control caching?

14 Answers 14

427

You have to use a more complex function like $.ajax() if you want to control caching on a per-request basis. Or, if you just want to turn it off for everything, put this at the top of your script:

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});
11
  • 2
    thank you! Is this even located in the jQuery documentation? Ahh... found it. Kind of berried. This had been kicking by butt for most of the day... Thanks again!
    – bytebender
    Commented Feb 19, 2010 at 20:30
  • 37
    All this cache: false does is append a number (I believe its a timestamp) to the end of a url when making the request. The other place to handle the cache settings are from the server or web app by setting various HTTP response headers, like Expires, Pragma, etc...
    – Astra
    Commented Mar 15, 2010 at 14:35
  • 2
    This piece of information hepled me greatly - it helped me locate a really nagging bug
    – Luke101
    Commented May 10, 2010 at 2:37
  • Love it! Now I don't have to use overly verbose .ajax calls and can use the shortcuts!
    – Gattster
    Commented Jun 1, 2011 at 1:05
  • 1
    Brilliant - I'd found this function but didn't know it would work on something as simple as loading a text document into a div using .load
    – Dan
    Commented Jan 25, 2012 at 16:35
116

Here is an example of how to control caching on a per-request basis

$.ajax({
    url: "/YourController",
    cache: false,
    dataType: "html",
    success: function(data) {
        $("#content").html(data);
    }
});
4
  • 7
    I like this way far better than just turning off all caching. Commented Nov 22, 2010 at 22:33
  • I also like this for not turning off all caching. Also, Look at this post also [link] stackoverflow.com/questions/4245231/… for filtering.
    – Dan Doyon
    Commented Mar 14, 2011 at 18:50
  • @Marshall the code here u gave not mention POST or Get type......so what is default for jquery?
    – Thomas
    Commented Mar 2, 2016 at 12:14
  • default method is GET
    – Rich T.
    Commented Apr 3, 2018 at 20:54
35

One way is to add a unique number to the end of the url:

$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());

Where you write uniqueId() to return something different each time it's called.

3
  • 2
    Even easier, just use (+new Date) (or new Date().getTime() if you're a stickler). See How do you get a timestamp in JavaScript?
    – thirdender
    Commented Jan 3, 2014 at 23:58
  • Ask a new question and link it here. If you did it right, you are generating completely new URLs, so they can't possibly be cached by the browser.
    – Lou Franco
    Commented May 6, 2015 at 19:09
  • used this to solve an unrelated issue. works a treat.
    – Alex
    Commented Feb 14, 2017 at 4:35
9

Another approach to put the below line only when require to get data from server,Append the below line along with your ajax url.

'?_='+Math.round(Math.random()*10000)

6
/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}
1
  • This nearly did the trick for me. Except the callback function has the incorrect "this" value. I changed the func() call to the following to fix this: func.call(elem, data, textStatus, XMLHttpRequest); Commented Feb 25, 2011 at 13:58
6

Sasha is good idea, i use a mix.

I create a function

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

And invoke for diferents parts of my page for example on init:

Init: function (actionUrl1, actionUrl2, actionUrl3) {

var ExampleJS= {

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

4

This is of particular annoyance in IE. Basically you have to send 'no-cache' HTTP headers back with your response from the server.

4

For PHP, add this line to your script which serves the information you want:

header("cache-control: no-cache");

or, add a unique variable to the query string:

"/portal/?f=searchBilling&x=" + (new Date()).getTime()
1
  • The cache: false option on the $.ajax function automatically adds the unique variable to the query string like your second suggestion.
    – Astra
    Commented Mar 15, 2010 at 14:36
3

Do NOT use timestamp to make an unique URL as for every page you visit is cached in DOM by jquery mobile and you soon run into trouble of running out of memory on mobiles.

$jqm(document).bind('pagebeforeload', function(event, data) {
    var url = data.url;
    var savePageInDOM = true;

    if (url.toLowerCase().indexOf("vacancies") >= 0) {
        savePageInDOM = false;
    }

    $jqm.mobile.cache =  savePageInDOM;
})

This code activates before page is loaded, you can use url.indexOf() to determine if the URL is the one you want to cache or not and set the cache parameter accordingly.

Do not use window.location = ""; to change URL otherwise you will navigate to the address and pagebeforeload will not fire. In order to get around this problem simply use window.location.hash = "";

1
  • 1
    what is the $jqm? $jqm=$? $.mobile.cache is undefined
    – Luciuz
    Commented Feb 19, 2013 at 7:34
3

If you want to stick with Jquery's .load() method, add something unique to the URL like a JavaScript timestamp. "+new Date().getTime()". Notice I had to add an "&time=" so it does not alter your pid variable.

$('#searchButton').click(function() {
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());            
});
2

You can replace the jquery load function with a version that has cache set to false.

(function($) {
  var _load = jQuery.fn.load;
  $.fn.load = function(url, params, callback) {
  if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
  }
    var selector, type, response,
      self = this,
      off = url.indexOf(" ");

    if (off > -1) {
      selector = stripAndCollapse(url.slice(off));
      url = url.slice(0, off);
    }

    // If it's a function
    if (jQuery.isFunction(params)) {

      // We assume that it's the callback
      callback = params;
      params = undefined;

      // Otherwise, build a param string
    } else if (params && typeof params === "object") {
      type = "POST";
    }

    // If we have elements to modify, make the request
    if (self.length > 0) {
      jQuery.ajax({
        url: url,

        // If "type" variable is undefined, then "GET" method will be used.
        // Make value of this field explicit since
        // user can override it through ajaxSetup method
        type: type || "GET",
        dataType: "html",
        cache: false,
        data: params
      }).done(function(responseText) {

        // Save response for use in complete callback
        response = arguments;

        self.html(selector ?

          // If a selector was specified, locate the right elements in a dummy div
          // Exclude scripts to avoid IE 'Permission Denied' errors
          jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :

          // Otherwise use the full result
          responseText);

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
      }).always(callback && function(jqXHR, status) {
        self.each(function() {
          callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
        });
      });
    }

    return this;
  }
})(jQuery);

Place this somewhere global where it will run after jquery loads and you should be all set. Your existing load code will no longer be cached.

1
  • Really nifty code, but one comment: You check for one space that would separate the URL from the selector, if any. However, jQuery documentation states: "If one or more space characters are included in the string". You might rather do: var [url, selector] = url.split( /[\s]+/ );
    – Jacques
    Commented Jun 15, 2023 at 8:18
0

Try this:

$("#Search_Result").load("AJAX-Search.aspx?q=" + $("#q").val() + "&rnd=" + String((new Date()).getTime()).replace(/\D/gi, ''));

It works fine when i used it.

0

I noticed that if some servers (like Apache2) are not configured to specifically allow or deny any "caching", then the server may by default send a "cached" response, even if you set the HTTP headers to "no-cache". So make sure that your server is not "caching" anything before it sents a response:

In the case of Apache2 you have to

1) edit the "disk_cache.conf" file - to disable cache add "CacheDisable /local_files" directive

2) load mod_cache modules (On Ubuntu "sudo a2enmod cache" and "sudo a2enmod disk_cache")

3) restart the Apache2 (Ubuntu "sudo service apache2 restart");

This should do the trick disabling cache on the servers side. Cheers! :)

0

This code may help you

var sr = $("#Search Result");
sr.load("AJAX-Search.aspx?q=" + $("#q")
.val() + "&rnd=" + String((new Date).getTime())
.replace(/\D/gi, ""));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.