user1444027
user1444027

Reputation: 5241

Timed AJAX request, reload if content is different

I am using the following script to check if the content of currentshow.php and #current-show (on the existing page) are different. If they are different then I want to replace #current-show with currentshow.php:

jQuery(document).ready(function() {

var auto_refresh = setInterval(
    function (){
        function getcurrentshow(){
         var result = null;
         jQuery.ajax({
            url: '/currentshow.php',
            type: 'get',
            dataType: 'html',
            async: false,
            success: function(data) {
                result = data;
            } 
         });
         return result;
        }

        gcs = getcurrentshow();
        cs = jQuery('#current-show').html();
        if (gcs != cs){
            jQuery('#current-show').load('/currentshow.php');
        };
    }, 1000);
)};

I do console.log(gcs) and console.log(cs) and both return exactly the same thing in the JS console. However, the content reloads every second anyway.

Any idea what I am doing wrong?

Upvotes: 0

Views: 37

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You code actually has some drawbacks.

  1. You are making sync request which is a bad practice and even deprecated in main UI thread.
  2. You are making requests twice.
  3. You are using setInterval what if network lags for a few seconds?
  4. You are accessing the DOM to check if data was actually changed.

Consider the following fiddle. http://jsfiddle.net/Pxe2V/

var prev; //store previous data here
function update() {
    $.get('/currentshow.php').done(function(data) {
        if(data !== prev) { //if data was changed perform DOM manip.
            $('#current-show').html(prev = data);    
        }
    }).always(function() { //Launch next request when prev is done.
        setTimeout(update, 1000);    
    });            
}

update();

Upvotes: 2

Victory
Victory

Reputation: 5890

I think you should do your comparison inside the success callback. Make sure that current show does in fact return the innert HTML and not the "#current-show" element

 var auto_refresh = setInterval(
    function (){

      var result = null;
      jQuery.ajax({
         url: '/currentshow.php',
         type: 'get',
         dataType: 'html',
         async: false,
         success: function(data) {
             result = data;
             cs = jQuery('#current-show').html();
             if (cs != result) {
               jQuery('#current-show').html(result);
             }
         } 
      });

  }, 1000);

Upvotes: 1

Related Questions