Matt Welander
Matt Welander

Reputation: 8548

prevent caching of xmlhttp request

I have a javascript that retrieves a JSON through an ajax request. My problem is that the browser starts caching the response to this request, so I don't actually get the latest data from the server, but instead an older cached version.

    $.getJSON( self.data('pathAllGet'), function( json ) {
        self.data('galleryData',json);
        self.data(render(self));
    });

Upvotes: 1

Views: 220

Answers (1)

Quentin
Quentin

Reputation: 943108

Don't use the getJSON method. It is a convenience function for common use cases that don't cover your needs.

Use ajax instead. That allows you to include cache busting.

$.ajax({
  dataType: "json",
  url: self.data('pathAllGet'),
  success: function( json ) {
    self.data('galleryData',json);
    self.data(render(self));
  },
  cache: false
});

By adding cache: false, you tell jQuery to append a uniqueish string to the URL. This means that next time you request the data, you'll get a different URL which the browser won't have in its cache.

Alternatively, set up your caching rules on the server.

Upvotes: 1

Related Questions