How to set cache false for getJSON in jQuery?

I am using getJSON to fetch the results from server side but facing browser cache problems. I want the cache to be false. I tried using this just before my getJSON call.

 $.ajaxSetup({
                cache: false
            })

But I am not getting the expected results. It still shows the old results.

I also identified some other solutions such as using .ajax but I really don't want to use that.


Solution 1:

Your code just needs a trigger for it to be enabled.

This will allow you to disable cache in all future ajax

$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});

Hope it helps :)

Solution 2:

You can use either this, that will disable cache globally:

$(document).ready(function() {
  $.ajaxSetup({ cache: false });
});

or that, instead of $.getJSON, to disable the cache just for such request:

$.ajax({
    cache: false,
    url: "/path/to.json",
    dataType: "json",
    success: function(data) {
        ...
    }
});

Solution 3:

semente's and bonesnatch's answers are correct, but if you want to use $.getJSON and elsewhere take advantage of it's caching (you don't want to set the cache to false for all calls), but you want to bust the cache just for a single call, you can inject a timestamp into data property of $.getJSON(). By adding a unique value to the query string of the request, the request will always be unique and not be cached by the browser - you will always get the latest data.

Long version:

var ts = new Date().getTime();
var data = {_: ts};
var url = '/some/path.json';

$.getJSON(url, data);

All in one version:

$.getJSON('/some/path', {_: new Date().getTime()});

Both result in the following request:

/some/path.json?_=1439315011130 

where the number at the end is the timestamp for the moment that the code is called and will therefore always be unique.