2

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.

edwardsmarkf
  • 1,387
  • 2
  • 16
  • 31

1 Answers1

2

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.

John Kossa
  • 459
  • 2
  • 8
  • yup - i tried running it WITHOUT the chrome-debugger (which occasionally seems to introduce a few issues of its own). is there any way around this? – edwardsmarkf Jan 05 '16 at 20:51
  • Try putting it in its own function and dropping a debugger statement in front of the function call. Then you can step into the function and when you finish stepping through it, the context will end and the call will be sent. – John Kossa Jan 05 '16 at 20:54
  • Just keep in mind that send() doesn't actually send the call. It rather just flags the call to be sent, and the native code in the browser will take care of it when you give control back to the browser. – John Kossa Jan 05 '16 at 20:56
  • john - thank you SO MUCH! now i am wondering if the jquery-ajax had the same issue. EDIT - no - i forgot that jQuery-ajax kept giving me "parsererror no conversion from text to binary" which is why i switched over to XMLHttpRequest in the first place. – edwardsmarkf Jan 05 '16 at 21:02