11

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?)?

chRyNaN
  • 3,592
  • 5
  • 46
  • 74
  • 1
    You need to create a new request object for an other request. You should not call `send` multiple times on the same object. – Bergi Jan 23 '15 at 00:20
  • @Bergi Wouldn't it be more practical to just re-call the open method on the object? Or will that not work? – chRyNaN Jan 23 '15 at 00:57
  • 1
    I don't see how that would be "more practical". What do you think you gained by [reusing the object](http://stackoverflow.com/q/11079543/1048572)? IIRC, some older browsers had a few bugs with that. – Bergi Jan 23 '15 at 02:46
  • 1
    Well, though not dramatic at all in this case, you save garbage collection time for one. If it is a once use then throw away object, that is just poor design. . – chRyNaN Jan 23 '15 at 16:20
  • 2
    "not dramatic" might even be a bit overstated :-) These objects are fairly low-cost (and seldomly needed), so I'd really go for simplicity first. – Bergi Jan 23 '15 at 22:47

1 Answers1

8

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.

Arnaud JOLLY
  • 171
  • 1
  • 3
  • Yes, I'm aware of websockets. But back to XMLHttpRequest, couldn't I just re-use the same object just by calling open again on that object, or will that not work? – chRyNaN Jan 23 '15 at 00:56
  • 1
    Nope, you have to recreate a `XLMHttpRequest` for each "request" you want to do. – Arnaud JOLLY Jan 24 '15 at 10:18