Prevent AJAX URL caching »
FERDY CHRISTANT - JUN 29, 2006 (02:16:50 PM)
![]() |
AJAX development has a number of caveats. This tip discusses how to solve a simple yet important problem. Imagine you have a form with a button on it. When a user clicks the button, an action will be run, yet the page will not be refreshed. This is a very typicaly AJAX scenario. The remote action that gets called, is triggered by a URL, i.e. the URL of a script. The URL is triggered each time the button is clicked. This is where the problem comes in. Once the response of the first time the URL is triggered is received, IE caches that response. Thus, any subsequent calls to the same URL will not give back realtime data, instead the cached response. AJAX almost always depends on fresh data, so this is a crucial problem. |
<input type="button" onclick="
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'yourscript.php?ms=' + new Date().getTime(), true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert('Status is ' + xmlhttp.status);
if (xmlhttp.status == 200) {
alert('Status is ' + xmlhttp.status);
}
}
// send the request
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send();
;" value="Test">
Note that the code fragment above uses Sarissa for simplified AJAX development. If you like to use the code fragment you should therefore include the Sarissa library, and most likely also change the first part of the remote call URL.




Comments: 6
Reviews: 4
Average rating:
Highest rating: 5
Lowest rating: 1
COMMENT: ANDREI KOUVCHINNIKOV
JUL 4, 11:50:46
Strangely, caching does not seem to happen when same code is run in VB. «
COMMENT: ANONYMOUS
DEC 25, 04:48:52 PM
COMMENT: BELLYBUTTON
AUG 15, 2008 - 12:47:08
COMMENT: DON JONES
OCT 7, 2010 - 01:58:28 AM
COMMENT: RANZENFRÖHN
OCT 25, 2010 - 12:32:52
COMMENT: SABASTIAN
NOV 15, 2011 - 20:59:36