henderunal
henderunal

Reputation: 749

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?

Upvotes: 6

Views: 5326

Answers (4)

BiAiB
BiAiB

Reputation: 14122

xmlhttp.open("GET", url , false);

you open your XMLHttpObject as not asynchronous, that is to say, synchronous. So the page will freeze until the request url has been fully load.

try this:

xmlhttp.open("GET", url , true);

but, if you make an asynchronous, you'll have to define a callback handler with yourXmlHttpObj.onreadystatechange. You may look at Jorrit Schippers's answer for a complete use case.

Ajax calls are well documented over the internet and I suggest you to look for some docs/tutorials there.


Edit: For your last question, this is not exactly the right way, your code is not cross browser and will crash on some IE versions. Better use a framework like jQuery, so you simply dothis:

$.ajax({
 url: 'http://Whaterver.com/doc.xml',
 success: function( data ) {
   myDoc = data;
 }
});

Upvotes: 2

TonioElGringo
TonioElGringo

Reputation: 1037

The third parameter in XMLHttpRequest should be true for asynchronous request (meaning non-blocking transaction).

Quote from MDN Documentation

An optional boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send()method does not return until the response is received.

You should have a look there for examples on how to manage asynchronous requests.

Antoine

Upvotes: 3

Jorrit Schippers
Jorrit Schippers

Reputation: 1645

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();

Upvotes: 5

Steve
Steve

Reputation: 50573

This could be because you are sending a synchronous call to the server and it is waiting for a response. Rather use an asynchronous call to get the response:

xmlhttp.open("GET", url , true);

Upvotes: 2

Related Questions