Monday, 26 November 2018

Why can't I access the xhr object from inside my onreadystatechange handler?

Edit: I have removed the original code and replaced it with generalized code that anyone can run themselves to reproduce my problem:

var StripeCheckout = {
    configure: function(obj){
        obj.token();
    }
};

StripeCheckout.configure({
    token: function(token) {
        var request = new XMLHttpRequest();
        request.open('POST', 'http://localhost:3000/process-order');
        request.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        request.onreadystatechange = function() {
            debugger; // right here is the problem
        };
        request.send();
    }
});

For me, inside that anonymous function where the debugger statement is, request is mysteriously not defined and attempting to access it is a ReferenceError. That really mystifies me.

This is the weird part. If I create a throwaway variable defined at the top level, and set throwaway = request; right after creating the request object, then inside the onreadystatechange handler throwaway is defined and everything is okay, even though request is not defined.

I just tested it, and I can also access it as this at the point of the debugger statement, as expected. What gives? Why is request not defined?



from Why can't I access the xhr object from inside my onreadystatechange handler?

No comments:

Post a Comment