Stop jQuery .load response from being cached

dragonmantank picture dragonmantank · Oct 3, 2008 · Viewed 168.7k times · Source

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?

Answer

John Millikin picture John Millikin · Oct 3, 2008

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
});