jQuery’s getJSON failing randomly in Internet Explorer
getJSON is perhaps the easiest method to erm get JSON with JavaScript using jQuery. JSON stands for JavaScript Object Notation, more information at Wikipedia.
The following piece of code is a really simple way to implement AJAX using the jQuery library:
function(data) {
// go do this, go do that…
}
);
I have a setInterval and each time Firefox will get the updated chat JSON every 10 seconds. But Internet Explorer has some issues, often return with old data.
And this is because of cache! The following code re-implements the above code to avoid caching issues.
url: "./chat.php?type=json",
cache: false,
dataType: "json",
success: function(data) {
// Go do this, go do that…
}});
To get back your data as JSON, remember to set dataType as “json”.
What cache: false does is that it appends a string of numbers such as “_=1211276828515″ at the end of the URL.
GET http://localhost/chat.php?type=json&_=1211276828515
This number increases, it might be string of time in milliseconds or something, but it makes the browser thinks that the request is different from the previous.
I sat in front of the computer for an hour trying to figure out what’s wrong with my JavaScript or PHP code. Defeated by cache.
Possibly related:
Thanks for posting, I knew it was a cache issue but couldn’t imagine IE cached ajax calls. IE never ceases to amaze. Thanks for posting the no cache functionality in $.ajax.
Jul 01
nice! can i assume adding a random get var in getJSON would do the same thing?
Jul 03
@Timothy: Yup, that does the same thing too. If you’re using jQuery, it’s better to use their no cache function as that takes uses a time string which is not random and will not repeat itself.
Jul 03
thanks kahwee, this has been a big help to me! Took me a while to figure out IE was caching my ajax calls.
Jul 22
Thanks alot! working with a perl upload-script along with an ajax progressbar and it drive me crazy trying to figure out why it randomly worked/not worked in ie
, now its silk smooth. big up!
Sep 02
im working in a similar code, but my $.get function do nothing on IE, but in FF works fine
bla bla bla.. things to do…..
i put an alert at the beggining of here, FF says hello world fine but IE says nothing…
});
anyone..???
Sep 03
Thanks for this information!
I had the same problem in IE7. Using “cache: false” it finally works.
Jan 25
Thanks so much – you’ve fixed my bug too!
Feb 02
If you wish to continue using $.getJSON you can try this:
$.ajaxSettings.cache = false
Feb 07
Thanks to Heathen,
this works fine!
Feb 20
Thanks for the tip, I am sure that is going to save me a lot of time.
Apr 11
Ai pessoal, mais facil e simples utilize o codigo abaixo
$.ajaxSetup({ cache: false });
$.getJSON(“ajax/menu.aspx”, function(data) {
// Codigo
}
Oct 23