Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.get doesn't receive latest version of file on server [duplicate]

Possible Duplicate:
Prevent caching of AJAX call

I'm using jQuery to read a tiny text file on a web server:

jQuery.get('scores.txt', function(data) {
    parseScores(data);
});

This nearly works as it should -- but it doesn't reliably load the latest version of the file. Even if story.txt has changed, refreshing the page returns exactly the same value for data.

The server is standard Mac OS Apache, with no caching enabled, and it's the same machine as the client -- so in theory there are no other caches sitting between me and it.

If I load http://127.0.0.1/scores.txt into the browser then it always opens the latest version.

Looking at the Apache log, for the times the page fails to update, the jQuery GET request never reaches the server.

I have a suspicion that I might need to move this question to serverfault.com, but can anyone see a problem with my JavaScript that would make it behave in this way?

Is there any way of using JavaScript/jQuery to force the browser to request a new copy of the file?

Thanks in advance.

like image 1000
James Avatar asked Dec 14 '12 10:12

James


2 Answers

Try adding cache: false to your AJAX options:

jQuery.ajax({
    url: 'scores.txt',
    dataType: 'text',
    type: 'GET',
    cache: false,
    success: parseScores
});

jQuery will automatically add a cache-preventing timestamp to each request.

like image 63
Blender Avatar answered Nov 16 '22 14:11

Blender


You can add a unique identifier to each request to stop the browser caching the response. Just because the client is on the same device as the web server, that does not stop the browser caching the response (nor will it prevent some proxy servers getting involved in the right environment).

jQuery.get('scores.txt', {
    now: jQuery.now()
}, function(data) {
    parseScores(data);
});
like image 6
Matt Avatar answered Nov 16 '22 15:11

Matt