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:

$.getJSON("./chat.php", { type: 'json' },
  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.

comments powered by Disqus