xneonz
xneonz

Reputation: 1

XMLHttpRequest contains non-empty response but XMLHttpRequest.response is <emptystring>

I'm sending HTTP requests and receiving responses with the following code:

var xhr = new XMLHttpRequest()
var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if (userInfo.type == 2) {
    userType = 'professor'
}
xhr.onreadystatechange = function() {
    try {
        if (this.status == 200 && waiting) {
            waiting = false;
            var courses
            try {
                courses = JSON.parse(xhr.response)
            } catch (jerr) {
                courses = []
            }
            sup.courseArray = courses;
            console.log(sup.courseArray)
            sup.render()
        }
    } catch (err) {}
}
xhr.open('GET', 'http://localhost:8080/course/read/' + userType + 'Id/' + userId)
xhr.send()

As you can see, I'm only accessing response in the callback, so the server has responded and xhr has been initialized at that point. If I simply call console.log(xhr), I can clearly see response is a non-empty string:

response: "[{\"id\":1,\"professorId\":1,\"name\":\"java\",\"code\":\"CS1017\"}]"

However, if I call console.log(xhr.response), I get

<empty string>

Does anyone know why I'm seeing this discrepancy?

Upvotes: 0

Views: 167

Answers (2)

ocrdu
ocrdu

Reputation: 2183

this.status == 200 will be true as soon as xhr.readyState == 2, but the request will not be completely fulfilled until xhr.readyState == 4; at readyState == 2 response will still be empty.

console.log(xhr) will eventually show the status at readyState == 4, but that's 2 readyStates later than when your code tries to access xhr.response.

You have to check that both status == 200 and readyState == 4 are true to be sure a complete response has arrived.

Upvotes: 1

Rogelio
Rogelio

Reputation: 1094

why not try using using JS native fetch instead

var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if(userInfo.type == 2) {
   userType = 'professor'
}

fetch('http://localhost:8080/course/read/' + userType + 'Id/' + userId)
.then(r => r.json())
.then((response) => {
    waiting = false;
   sup.courseArray = response;
   console.log(sup.courseArray);
   sup.render();
})
.catch((e) => {
     waiting = false;
     console.log(e);
});

Upvotes: 0

Related Questions