1

I am trying to make a simple ajax class for a chrome extension. I get an undefined error Uncaught TypeError: Cannot read property 'readyState' of undefined when I try to run the code. What seems to cause this issue?

function ajax(arguments, callback) {
    this.xhr = new XMLHttpRequest();
    this.xhr.open(arguments.requestType, arguments.requestUrl + arguments.requestParameters, true);
    this.xhr.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            requestedData = JSON.parse(this.responseText);
            callback(requestedData);
        }
    }
    this.xhr.send();
}

var ajaxRequest = new ajax({ 
    requestType: 'GET',
    requestUrl: 'http://ezswag.com/bots/terms.php',
    requestParameters: ' ',
    }, function(json) {
        //console.log(json);  => json {apple: "red", cheery: "red"}
        return json;
    });

    console.log(ajaxRequest);

(Updated code, and working)

3 Answers 3

4

The value of this depends on how the function is being called.

When you call the ajax function as a constructor (note that convention says you should start constructor function names with a capital letter) this is the instance being created.

In the readyState function, this is the XMLHttpRequest object.

All your references to this.xhr inside the readyState function should be simply this

Sign up to request clarification or add additional context in comments.

1 Comment

thank you. I updated the code with a callback. Is there a way to access the json data from the callback outside the function from the variable ajaxRequest ?
1

you can't use this.xhr inside the function. This does a reference to the current function and not what do you think.

Use a temp variable like this :

var self = this;

this.xhr.onreadystatechange = function() {
    if (self.xhr.readyState === 4 && self.xhr.status === 200) {
        requestedData = JSON.parse(self.xhr.responseText);
        console.log(requestedData);
    }
}

Comments

1

In your onreadystatechange implementation, this is not what you think it is. You need to capture the scope of your ajax function and use that in your callbacks.

function ajax(parameter) {
    var that = this;
    this.xhr = new XMLHttpRequest();
    this.xhr.open(parameter.requestType, parameter.requestUrl + parameter.requestParameters, true);
    this.xhr.onreadystatechange = function() {
        if (that.xhr.readyState === 4 && that.xhr.status === 200) {
            requestedData = JSON.parse(that.xhr.responseText);
            console.log(requestedData);
        }
    }
    this.xhr.send();
}

1 Comment

Why not just this instead of that.xhr inside the callback?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.