0

In my javascript code I have:

function getThing(){
    var url = "myhost/thing";
    var x = new XMLHttpRequest();
    x.open("GET", url, false);
    x.onload = function (){
        return x.responseText
    }
    x.send(null);
}

console.log(getThing())

And console log gives me undefined.

What am I doing wrong?

Coffee
  • 2,063
  • 8
  • 24
  • 57
  • 1
    You are not returning anything from `getThing()` function. AJAX is asynchronous, so when you are calling getThing() you are not going to wait for the ajax to return value. – Unamata Sanatarai Mar 30 '17 at 18:49
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – abhishekkannojia Mar 30 '17 at 18:49
  • And how do I make the call synchronous? – Coffee Mar 30 '17 at 18:50
  • It's not async. Delete the `x.onload` block and return `x.responseText` after `x.send` – James Mar 30 '17 at 19:42

1 Answers1

0

Your HTTP request is executed asynchronously, and getThing is not returning anything other than undefined. Instead, your onload handler is returning the requested value, which is not used.

Instead, you need to wait with logging until the call has returned:

function getThing(){
    var url = "myhost/thing";
    var x = new XMLHttpRequest();
    x.open("GET", url);
    x.onload = function (){
        console.log(x.responseText);
    }
    x.send(null);
}

getThing();
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94