Swapnil Walivkar
Swapnil Walivkar

Reputation: 295

Cached data showing on browser on jquery ajax call

I have following ajax call with me which is written in jquery: which takes continuous response from controller in json format and displays it on screen by setting values (Not there in following code).

$(function() {
 $(".master_status").hide();
   setInterval(
    function() {
         $.ajax({
         type : "Get",
         url : "getDeviceInfo.htm",
         success : function(response) {
           if(response != null){

           }
         } ,
    error : function(e) {
        }
    });
    }, 500);

    }

And I am getting data from controller in every half second. But sometimes it shows previous state data for a fraction of second. I traied cache:false, in ajax call and increasing and decreasing interval time but still problem exists. Any suggestions?

Upvotes: 0

Views: 270

Answers (2)

Aman Arora
Aman Arora

Reputation: 1252

Reason for the old data getting rendered:

Browsers struggle hard to make your web experience easier and faster. For that they even cache the response of requests, so that if again you call the ame page. They show it a local copy rather than going to server again. But it becomes a problem sometimes.

Solution: Try appending a unique request parameter at the end of url. So if you are going to url (http://something.com/data), try changing it to

  http://something.com/data?someUniqueThing 

Unique thing: Generate a random number before sending the request and append it to url. So your ajax call will become :

 $(function() {
      $(".master_status").hide();
           setInterval(
              function() {
     $.ajax({
     type : "Get",
     url : "getDeviceInfo.htm?someUniqueThing",
     success : function(response) {
       if(response != null){

       }
     } ,
error : function(e) {
    }
});
}, 500);

}

It will not let the browser cache your requests. Why ? Because every second request will have a uniqueId at the end. Browser treats it as a new request but at server side,it will cause no side-effects.

Upvotes: 1

benjamin.d
benjamin.d

Reputation: 2871

This is well know issue in IE. Since your are using jquery, you could just use the cache attribute in you $.ajax call. Refer to the jquery API for more information.

Upvotes: 0

Related Questions