rus64
rus64

Reputation: 47

Javascript XmlHttpRequest callback

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?

Upvotes: 0

Views: 3676

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

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.

Upvotes: 1

Quentin
Quentin

Reputation: 944425

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?

Upvotes: 1

Related Questions