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?