Ajax async call not working, But disabling async does work |
Ajax async call not working, But disabling async does work |
PinGuy |
Dec 11 2019, 12:09 AM
Post
#1
|
Group: Members Posts: 8 Joined: 1-November 19 Member No.: 27,028 |
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 |
PinGuy |
Dec 11 2019, 07:39 AM
Post
#2
|
Group: Members Posts: 8 Joined: 1-November 19 Member No.: 27,028 |
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
|
Christian J |
Dec 12 2019, 08:55 AM
Post
#3
|
. Group: WDG Moderators Posts: 9,679 Joined: 10-August 06 Member No.: 7 |
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.
|
Lo-Fi Version | Time is now: 3rd June 2024 - 04:44 PM |