Reputation: 15
I have a div that calls a variable. When that variable changes, users need to refresh the page to see the new value. The variable is pulled from a separate PHP file.
I'm wondering if there's a way to use ajax to automatically update the div without the user refreshing the browser when it sees the PHP variable has been updated.
Upvotes: 0
Views: 3096
Reputation: 1210
You could periodically check if there have been any change to the variable using ajax and if that is the case you could update the div.
var previousValue = null;
function checkForChange() {
$.ajax({
url: 'http://example.com/getVariableValue.php',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
I havn't tested the code, but it should be something like that. Will get data from http://example.com/getVariableValue.php, you'll have to fill in some information about the AJAX request. I'm assuming you know how to modify the code for your specific data format, be it XML, JSON or text.
Upvotes: 3