Thursday, January 31, 2013

jQuery, AJAX, and Aggressive iOS Caching

This was the situation: A jQuery Mobile app was using jQuery AJAX requests to get JSON data from the server. Nothing crazy – except for maybe the server was a SharePoint server. I know – running one of those IS pretty crazy.

The requests from a typical browser worked as expected. No issues. With the ‘cache’ flag turned off, the server logs were showing each request come in when it was expected. Then came the iPad + iPhone testing. Initially all looked great. Except after the first request, subsequent requests never made it back to the server. WTH?

Turns out iOS does not honor the ‘cache’ flag in the jQuery AJAX object. In case you are not familiar with this, here is what a typical jQuery AJAX request looks like:

$.ajax({
url: ws_url,
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: true,
cache: false, //to cache or not to cache
success: function (data) {
//yes
},
error: function (jqXHR, exception, errorThrown) {
//no
}
});

Caching is good and all, but most of the time you need to control it, like if you had a refresh button. This is usually done by changing the ‘cache’ flag to false. To account for the iOS family, you must also add the cache-control header and set it to ‘no-cache’ – which looks like this:




$.ajax({
url: ws_url,
type: "POST",
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
headers: { "cache-control": "no-cache" },
success: function (data) {
//yes
},
error: function (jqXHR, exception, errorThrown) {
//no
}
});

Hope this saves someone some time.

 
© I caught you a delicious bass.
Back to top