-2

I am using below code to capture response but unable to get, please let me know what I am missing here.

function testcall() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://demo8951713.mockable.io/fusionchart', true);
    request.send();
    var response = this.responseText;
    alert(response);
}

testcall()
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
shri kant
  • 85
  • 12

2 Answers2

4

You have two problems.

First, this (in the context you are using it) does not refer to your XHR object.

Second, you are trying to read the response as soon as the request has been sent. You have to wait until the browser has received the response!

request.addEventListener("load", function () {
    var response = this.responseText;
    alert(response);
});

That change (moving the code to an event handler) also puts this in a context where it refers to the correct object.


Once you have fixed this, you are likely to want to try to return the value. Before you do, read this question.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

you are missing the callback function

request.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        callback(xhr.response);
    }
}

for more details, refer https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response#Example

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
Nikhil
  • 21
  • 1
  • 5