Search code examples
javascriptxmlhttprequestxmlhttprequest-states

XMLHttpRequest does not seem to do anything


i have been trying very unsuccessfully to download a binary file from my server using jquery-ajax, which i finally gave up. so now i am trying to use XMLHttpRequest instead. however, i cannot even get a simple example working.

strangely enough, this code does not appear to do anything. i copy/pasted this from w3schools and this example is near identical to many other examples. it does not work for me in either chrome or FF:

 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       // Action to be performed when the document is read;
    }
};
xhttp.open("GET", '/blah/blah/output.png', true);
xhttp.send();

we go into the onreadystatechange function only once, on the open() statement with an xhttp.readyState equal to one, but not on the send() step. i should think it would at least throw some kind of error rather than do nothing at all.

also, as an experiment, i purposely fed the open() a bad url - but again no reply.

can anybody tell me what i might be doing wrong?

thank you very much.


Solution

  • Your code looks correct to me, which points to some external cause.

    Is your code flowing all the way through to the end of the execution context? Browsers will hold onto network requests until the engine yields back to the browser.

    For instance:

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (xhttp.readyState == 4 && xhttp.status == 200) {
       // Action to be performed when the document is read;
      }
    };
    xhttp.open("GET", '/blah/blah/output.png', true);
    xhttp.send();
    
    while(true){}
    

    will never send the call.