jquery - Timed AJAX request, reload if content is different -
i using following script check if content of currentshow.php
, #current-show
(on existing page) different. if different want replace #current-show
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 console.log(gcs)
, console.log(cs)
, both return same thing in js console. however, content reloads every second anyway.
any idea doing wrong?
you code has drawbacks.
- you making sync request bad practice , deprecated in main ui thread.
- you making requests twice.
- you using
setinterval
if network lags few seconds? - you accessing dom check if data changed.
consider 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 changed perform dom manip. $('#current-show').html(prev = data); } }).always(function() { //launch next request when prev done. settimeout(update, 1000); }); } update();
Comments
Post a Comment