Search code examples
javascriptxmlhttprequest

The page freezing on XMLHttpRequest


I am working on a website. We are requesting for new alarms in every 1 min. We are using Javascript and c# handlers for that operation. The javascript part is :

var url = "/myurl";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url , false);
xmlhttp.send();
var xmlDoc = null;
xmlDoc = xmlhttp.responseXML;

What could be the reason of my problem?

One more thing. Is this the right way?


Solution

  • You should use asynchronous code. Because your code is synchronous at this moment, it will halt the page execution after xmlhttp.send().

    Try something like:

    var url = "/handlers/doS.ashx?id=s101";
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url , true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var xmlDoc = xmlhttp.responseXML;
            // Do something here
        }
    }
    xmlhttp.send();