Posted by: PinGuy Dec 11 2019, 12:09 AM
I am having difficulties with an async call, The server does take a while to respond (about 1.5-2 secs). If I open the request synchronously, it works as expected, but the browser stalls until the reply is received, and gets quite unresponsive. If I open the request asynchronously, the json reply never somes, although on the server I see all the requests are being received.
Code snippet follows (I call Check() on button click):
CODE
var Request = null;
if (window.XMLHttpRequest) { Request = new XMLHttpRequest(); }
function Check() {
Interval = setInterval(doCheck, 1000);
}
function doCheck() {
if (!Request) { alert("Browser does not support Ajax!"); return; }
Request.open("GET", "checksignal", true);
Request.onreadystatechange = function () {
if (Request.readyState == 4 && Request.status == 200) {
var Reply = JSON.parse(Request.responseText);
if (Reply) {
document.getElementById("RX").innerHTML = "RX level: <b>" + Reply.rx + "dBm</b>";
document.getElementById("TX").innerHTML = "TX level: <b>" + Reply.tx + "dBm</b>";
}
}
}
Request.send();
}
function Cancel() {
clearInterval(Interval);
}
Am I doing something wrong? Is it possible to make this work async? Or should I stick with synchronous calls and live with it?
I though that moving Request.open to the Check() function would work, but if I do this I get "InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED."
Since Request is a global, and I don't close it at all, I don't understand this message
TIA
Posted by: PinGuy Dec 11 2019, 07:39 AM
Ooops! The interval was too quick for the function to get the reply before a new call to open() was made. After changing it to 2500, it started to work as expected
Posted by: Christian J Dec 12 2019, 08:55 AM
I don't do Ajax, but in general it might be safer to confirm that the reply has been recieved, rather than using a delay and hope that the reply arrives in time.