This script is throwing this error every half second:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. signals.js:9
req.onreadystatechange signals.js:9
update_table signals.js:26
req.onreadystatechange
This is signals.js - I want it to reload every 5 seconds and if there is new content, to trigger the "Sound" alert.
function update_table()
{
var old_table = document.getElementById('signals').innerHTML;
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.status == 200)
{
if(req.readyState == 4)
{
var new_table = req.responseText;
alert(old_table);
alert(new_table);
if(old_table != new_table)
{
//play sound
alert("Sound!");
}
alert("Refresh!");
setTimeout(update_table, 5000);
}
}
}
var link = "table.php?refresh=true";
req.open("GET", link, false);
req.send();
}
First check if the req.readyState equals 4 and then check if the req.status equals 200. The HTTP status code isn't set before the request is processed, so you can't use it before the readyState equals 4.
You can check this link for more info about the onreadystatechange event.
You need to first check whether req.readyState
equals to 4
(means DONE
), and only then check for req.status
:
function update_table() {
var old_table = document.getElementById('signals').innerHTML;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
// Here: first check for readyState
if(req.readyState === 4 && req.status == 200) {
var new_table = req.responseText;
alert(old_table);
alert(new_table);
if(old_table != new_table)
{
//play sound
alert("Sound!");
}
alert("Refresh!");
setTimeout(update_table, 5000);
}
}
var link = "table.php?refresh=true";
req.open("GET", link, false);
req.send();
}
See XMLHttpRequest doc for details.