0

Trying to get my head around http requests and asynchronous javascript behaviour.

function httpGetAsync(url, callback){
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
      console.log(xmlHttp.responseText); // prints the ip address
      callback(xmlHttp.responseText);
    }
  }
  xmlHttp.open("GET", url, true)
  xmlHttp.send(null);

}

httpGetAsync("http://httpbin.org/ip", function(){
   console.log(this); // doesn't print the ip address
})

The http request is just a simple one that returns a json formatted ip address of the get request. In the function definition the ip address can be printed to the console just fine however in the callback the console prints out the window object. this is probably the wrong thing to use, how do I access the data in xmlHttp.responseText in the callback?

rus64
  • 67
  • 1
  • 10

2 Answers2

1
callback(xmlHttp.responseText);

You are calling a function. You are passing it an argument.

function(){
   console.log(this); // doesn't print the ip address
}

Your function is not expecting to receive any arguments. Change that, then use that argument.

function(my_argument){
   console.log(my_argument);
}

See also How does the “this” keyword work?

Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
1

You're calling callback(xmlHttp.responseText), so...

httpGetAsync("...", function(response) {
    console.log(response);
});

Simple!

One small point: I would recommend putting the .open call before the onreadystatechange, because in some (older) browsers calling .open will reset event handlers.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540