How to eliminate cached data error from AJAX

Since AJAX load method uses jQuery get method internally, So that you may get cached data.

To remove this this error make sure to send a unique key as part of the query string and it will give you the new content /result /uncached data from server.

A simple ajax function

function unassign_shop(full_id)

{
var n=full_id.length;
var id=full_id.substr(9,n-9);
var commentContainer = $("div#unassigned_" + id).parent();
var str = 'remove_shop=removed&salesman_id=' + <?php echo $salesman_id; ?> + '&assign_id=' + id ;
commentContainer.slideUp('slow', function() {$("div#assigned_" + id).remove();});
 
document.getElementById("unassigned").innerHTML="<img src='../design/content/loading.gif' title='loading' />";
 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("unassigned").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax/fetch_unassigned.php?"+str,true);
xmlhttp.send();
}

If you use some functions like above  then you will get only the cached data because the query string is same as in most cases.

var str = 'remove_shop=removed&salesman_id=' + <?php echo $salesman_id; ?> + '&assign_id=' + id ;

One solution is to pass timestamp value as part of the query string so that it will generate a unique request.

var date = new Date().getTime();

var str = 'remove_shop=removed&salesman_id=' + <?php echo $salesman_id; ?> + '&assign_id=' + id + 'date==' + date ;
 
Then the query string is always different so you will not get any cached data.

 

 
You can leave a response, or trackback from your own site.

Leave a Reply