How to set cache: false in jQuery.get call
Asked Answered
A

7

81

jQuery.get() is a shorthand for jQuery.ajax() with a get call. But when I set cache:false in the data of the .get() call, what is sent to the server is a parameter called cache with a value of false. While my intention is to send a timestamp with the data to the server to prevent caching which is what happens if I use cache: false in jQuery.ajax data. How do I accomplish this without rewriting my jQuery.get calls to jQuery.ajax calls or using

$.ajaxSetup({
    // Disable caching of AJAX responses
    cache: false
});

update: Thanks everyone for the answers. You are all correct. However, I was hoping that there was a way to let the get call know that you do not want to cache, or send that value to the underlying .ajax() so it would know what to do with it.

I a. looking for a fourth way other than the three ways that have been identified so far:

  1. Doing it globally via ajaxSetup

  2. Using a .ajax call instead of a .get call

  3. Doing it manually by adding a new parameter holding a timestamp to your .get call.

I just thought that this capability should be built into the .get call.

Amora answered 12/1, 2012 at 19:55 Comment(4)
Show the full get() example?Environs
I like to pass the date/time of a file with the page (assuming I'm using a server-side scripting language), and then pass that with the request for the page as a querystring parameter. The reason I do this is because it allows caching, unless the page has actually changed.Acosta
Using cache:false appends a timestamp to the ajax/json request e.g. {"get":"modified"}&_=1394836303603 which broke my API requests. It took way too many hours to figure out what was adding the timestamp, as it is buried un the jQuery docs. Instead of using cache:false, just add your own timestamp, assuming your API will not care if you add an unknown parameter. Like this: {"get":"modified", "timestamp":"1394836303603"} This also lets you have finer control over what items are cached, and which are not.Bohol
Why you do not want to use $.ajaxSetup? It is a straight forward and gets the job done.Laxative
K
37

To me, the correct way of doing it would be the ones listed. Either ajax or ajaxSetup. If you really want to use get and not use ajaxSetup then you could create your own parameter and give it the value of the the current date/time.

I would however question your motives in not using one of the other methods.

Knowling answered 12/1, 2012 at 20:4 Comment(1)
Worth noting that in my particular app, I use cache: false in ajaxSetup (the majority of my calls are to json endpoints for payloads) and then I use $.ajax(..., cache: true) for any specific templates or things that I'll want cached. I prefer this anyway, as it makes things pretty explicit, and I'm calling more of the payload calls than static data.Boettcher
H
117

Add the parameter yourself.

$.get(url,{ "_": $.now() }, function(rdata){
  console.log(rdata);
});

As of jQuery 3.0, you can now do this:

$.get({
  url: url, 
  cache: false
}).then(function(rdata){
  console.log(rdata);
});
Hildebrandt answered 12/1, 2012 at 20:6 Comment(6)
thanks $.now() is the shorthand for new Date().getTime(). api.jquery.com/jQuery.nowAmora
You can now also do Date.now().Environs
Date.now() was only standardized in ECMA-262 5th edition. To polyfill for older engines, you may use: (Date.now ? Date.now() : (new Date().valueOf())) via developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Foreignborn
or, since we have jquery, just use what we've got. :)Hildebrandt
This should be the accepted answer... since the OP was asking specifically about $.get();Withhold
@SerjSagan i disagree with that, since prior to jQuery 3.0 the better option would be to use $.ajax. in 3.0, $.get can accept an options object too. :)Hildebrandt
E
64

I think you have to use the AJAX method instead which allows you to turn caching off:

$.ajax({
  url: "test.html",
  data: 'foo',
  success: function(){
    alert('bar');
  },
  cache: false
});
Environs answered 12/1, 2012 at 20:6 Comment(5)
IE9 caches and seems to really not like .getWarder
@Warder It shouldn't do if you set cache to false as per my answer.Environs
3 years later and I just lost half a day to the exact same problemEcotone
Six years later and I lost half a day to the same problem...Chou
8 years later this got me on stumped on vote feature AJAX call that relies on FormData and JSON return data (which means, I can not set ContentType: false). In reality, both of these options landed me here lolNupercaine
K
37

To me, the correct way of doing it would be the ones listed. Either ajax or ajaxSetup. If you really want to use get and not use ajaxSetup then you could create your own parameter and give it the value of the the current date/time.

I would however question your motives in not using one of the other methods.

Knowling answered 12/1, 2012 at 20:4 Comment(1)
Worth noting that in my particular app, I use cache: false in ajaxSetup (the majority of my calls are to json endpoints for payloads) and then I use $.ajax(..., cache: true) for any specific templates or things that I'll want cached. I prefer this anyway, as it makes things pretty explicit, and I'm calling more of the payload calls than static data.Boettcher
Q
7

Per the JQuery documentation, .get() only takes the url, data (content), dataType, and success callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax(), this is done with the beforeSend() method. But since .get() is a shortcut, it doesn't allow it.

It should be relatively easy to switch your .ajax() calls to .get() calls though. After all, .get() is just a subset of .ajax(), so you can probably use all the default values for .ajax() (except, of course, for beforeSend()).

Edit:

::Looks at Jivings' answer::

Oh yeah, forgot about the cache parameter! While beforeSend() is useful for adding other headers, the built-in cache parameter is far simpler here.

Quarters answered 12/1, 2012 at 20:6 Comment(0)
C
5

Set cache: false in jQuery.get call using Below Method

use new Date().getTime(), which will avoid collisions unless you have multiple requests happening within the same millisecond.

Or

The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)

$.ajaxSetup({ cache: false });
Collettecolletti answered 20/10, 2015 at 10:6 Comment(0)
O
3

Note that callback syntax is deprecated:

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Here a modernized solution using the promise interface

$.ajax({url: "...", cache: false}).done(function( data ) {
    // data contains result
}).fail(function(err){
    // error
});
Overpower answered 7/1, 2016 at 9:27 Comment(1)
It's 2023 and jQuery has zero plans to depreciate this in official builds. If you really want to be ahead of the game, remove jQuery entirely and use pure JS with fetch/async/await methods.Nupercaine
G
2

I'm very late in the game, but this might help others. I hit this same problem with $.get and I didn't want to blindly turn off caching and I didn't like the timestamp patch. So after a little research I found that you can simply use $.post instead of $.get which does NOT use caching. Simple as that. :)

Grenville answered 22/7, 2015 at 13:10 Comment(4)
I'm late too :) thanks for your contribution, it is working fineBaler
This is a bad advice as GET and POST are different verbs and should be used for different things. The same server url may be filtering by verb so for example a POST won't work if the server only expects a GET. Or even worse, the server may have different behaviors for GET and POST (which is very common actually).Traditor
@Andrew: If not jquery ajax always had the flaw to opt for get in the first place while that is not post and not the correct verb for ajax. So post is fine. and correct.Expostulate
I'm not sure if I understand what you mean. If you use a get instead of a post, that's wrong too. You should use get or post depending on what the endpoint does, and not use post to solve caching issues with get.Traditor

© 2022 - 2024 — McMap. All rights reserved.