12

Everything in the following code will work, except it will never fire the xhr.upload.onprogress event.

$(function(){

    var xhr;

    $("#submit").click(function(){
        var formData = new FormData();
        formData.append("myFile", document.getElementById("myFileField").files[0]);
        xhr = new XMLHttpRequest();
        xhr.open("POST", "./test.php", true);
        xhr.send(formData);

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                console.log(xhr.responseText);              
            }
        }

        xhr.upload.onprogress = function(e) {
           // it will never come inside here
        }
    });
}); 
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1534664
  • 3,258
  • 8
  • 40
  • 66
  • 2
    I think you must define your handlers before the calls to open. – VoidMain Jan 04 '13 at 15:49
  • Someone create the answer so I can accept it please. @VoidMain was correct. – user1534664 Jan 04 '13 at 16:13
  • @user1534664 xhr.upload.onprogress is working fine with IE but doesn't work with chrome and FF. Have you got any solution? Please do share your comments – Sankar M Sep 24 '14 at 08:39
  • 1
    @Sankar2.0 If you share your code I can have a look at it, but as it is right now I don't have enough information to conclude what your problem is. Make sure you use xhr.open() and xhr.send() after you declare your listeners, as that was my issue here. – user1534664 Sep 24 '14 at 17:57
  • you are correct! we set all the properties and open() before send(). that works for me. Great. Thanks! – Sankar M Sep 25 '14 at 05:06

1 Answers1

22

You should create the listeners before opening the connection, like this:

$(function(){

    var xhr;

    $("#submit").click(function(){
        var formData = new FormData();
        formData.append("myFile", document.getElementById("myFileField").files[0]);
        xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                console.log(xhr.responseText);              
            }
        }

        xhr.upload.onprogress = function(e) {
           // it will never come inside here
        }

        xhr.open("POST", "./test.php", true);
        xhr.send(formData);
    });
});

Hope that helps.

VoidMain
  • 1,987
  • 20
  • 22
  • 9
    You can open connection before handlers, but send need to be after. – jcubic Feb 13 '14 at 14:30
  • Hi, I have similar code like this but not working on mobile app. http://stackoverflow.com/questions/38581293/upload-using-xmlhttprequest-not-working-on-mobile Is xhr not working on react js? – Website Is Fun Jul 27 '16 at 02:55