Help - Search - Members - Calendar
Full Version: Ajax async call not working
HTMLHelp Forums > Programming > Client-side Scripting
PinGuy
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 blink.gif
TIA
PinGuy
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 smile.gif
Christian J
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.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2020 Invision Power Services, Inc.