chRyNaN
chRyNaN

Reputation: 3692

Does XMLHttpRequest object close after response received?

I'm trying to connect to the server using an XMLHttpRequest object to post data at different times. I create an object and "connect" to the server like so:

var xhr = new XMLHttpRequest();
xhr.open("post", location, true);
xhr.send(); //Is this send call needed to open the connection?

And at a later point in time, I call something like this:

xhr.send("Something to send");

However, looking at the developer console, it seems that only the initial request went through (and successfully responded). The second request doesn't seem to send. I'm trying to narrow down what could be the problem, so I thought: could the connection be closed once the response is received; Why would it be kept open? So, my question: Is the XMLHttpRequest object connection closed once it receives a response? If so, what's the best way to simulate a continuously open connection (to constantly reconnect?)?

Upvotes: 12

Views: 29184

Answers (1)

Arnaud JOLLY
Arnaud JOLLY

Reputation: 221

Yes, if you haven't tricked your server to keep it alive, it will be closed after the response is sent.

Maybe you want to look for websockets. But if you don't want to play with those, just create a new HttpRequest for each of your "request".

Basic communication with HTTP: 1 request -> 1 response -> closed!

Edit: Keep in mind that websockets is a new feature from HTML5 so it won't work for every browsers and if they work for some browsers, they maybe are not completely implemented.

Upvotes: 8

Related Questions