Reputation: 5241
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
Reputation: 45121
You code actually has some drawbacks.
setInterval
what if network lags for a few seconds?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
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