javascriptflashxmlhttprequestcallonreadystatechange

XMLHttpRequest methods order is important?


This code works fine:

function callFromFlex(url, method, payload) {
   console.log("call from Flex: " + method + " " + url + " " + payload);
   var xhttp = new XMLHttpRequest();
   xhttp.open(method, url, true);
   xhttp.setRequestHeader("Content-Type", "application/json");
   xhttp.onreadystatechange = function() {
    console.log(xhttp.readyState);
       if (xhttp.readyState == 4) { 
        console.log("trying to call flash...");
           // Callback to Flash here
           ...  
       }
   };

   xhttp.send(payload);
}

But this does not - onreadystatechange is never called:

function callFromFlex(url, method, payload) {
    console.log("call from Flex: " + method + " " + url + " " + payload);
    var xhttp = new XMLHttpRequest();

    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function() {
        console.log(xhttp.readyState);
        if (xhttp.readyState == 4) {    
            console.log("trying to call flash...");
            // Callback to Flash here;
            ... 
        }
    };
    xhttp.open(method, url, true);
    xhttp.send(payload);
}

I just moved xhttp.open(method, url, true) to another position and xhttp.onreadystatechange is never called. Checked with Firefox 45.0.2 and IE 11 and I believe it has nothing to do with the Flash player. The order shouldn't affect all this, should it?


Solution

  • The method order is absolutely important with XMLHttpRequest. The description of open starts with:

    Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.

    Until open has been called, the request is not fully initialized (allocation is not initialization, here) and the other methods are not guaranteed to work correctly.

    From some of the examples in the WhatWG spec, onreadystatechange ought to work, but I can't imagine setRequestHeader will. In fact, calling setRequestHeader before open should throw an InvalidStateError, it seems:

    If the state is not OPENED, throw an "InvalidStateError" exception.