Jon Watte
Jon Watte

Reputation: 7198

Why does this XMLHttpRequest POST fail to even connect to the server?

I have an XMLHttpRequest opened with the POST method, to a URL that I know exists because I've just done a GET on it. However, the send() call on the XHR doesn't actually open any connection to the server or send any data -- I've verified this with WireShark. Instead, it just fails the request, calls the onreadystatechange event handler, setting status to 0 (meaning, according to the spec, that the "error flag" is set).

But... there's no way for me to inspect WHAT is going wrong. I've tried this in FireBug, and the headers and body look OK; there is no response body or response headers. The line in the console output is a POST /url (x) where the (x) is a red circle with an X in it. No error reason is visible anywhere. That same line is not in the NET panel at all. This is probably a clue, but I don't know of what.

function save_edits(url, txt, cb)
  {
  var xhr = new XMLHttpRequest();
  console.log("'POST' " + url);
  xhr.open('POST', url, true);
  xhr.onreadystatechange = function(ev)
    {
    if (xhr.readyState == 4)
      {
      console.log('post complete status:' + xhr.status);
      cb();
      }
    }
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  var text = "&" + edit_what + "=" + escape(txt.replace(/\r/g, '\n'));
  try
    {
    xhr.send(text);
    }
  catch (e)
    {
    console.log('send() error: ' + e.toString());
    }

This outputs in the FireBug console:

  1. 'POST' http://mydomain.com/srv.json.section-xna.latest
  2. POST http://mydomain.com/srv.json.section-xna.latest source.js (line 70)
  3. post complete status:0

Line 1) is my console log statement.

Line 2) is the POST XHR request, which is red, with the circle-X showing failure.

Line 3) is the console log statement from the onreadystatechange handler.

There is no exception raised (I put that check in there just for paranoia) -- even if I make the open() be synchronous instead of asynchronous.

Again, this is not a server-side problem, because the request doesn't even make it onto the wire, and I don't know how to figure out why that is.

Upvotes: 1

Views: 4286

Answers (2)

Jon Watte
Jon Watte

Reputation: 7198

Thanks for the suggestions, everyone! It turns out to be a problem at a higher level.

The code that was calling the save function was then immediately calling window.location.reload() to see the new data, which ended up canceling the outstanding POST request.

Can't believe I had to go through WireShark AND Stack Overflow just to be able to see that problem...

Upvotes: 1

whoughton
whoughton

Reputation: 1385

Is the URL on your domain or an alternative domain? If it is an alternative domain you are most likely being blocked due to cross domain security issues.

Upvotes: 2

Related Questions