Reputation: 13
I have this problem, so I want to return the value received after an XMLHTTPRequest(), is this possible? If not, how would I go about achieving the same general idea? Here's what I have so far (It is obviously not working).
function something(url) {
var temp = getPage(url);
console.log(temp);
}
function getPage(url) {
var x = new XMLHTTPRequest();
x.onload = function() {
var html = x.responseText;
//CODE TO PARSE HTML TEXT
var variable = SOMETHING PARSED FROM HTML
return variable;
}
x.open("GET", url);
x.send();
}
Upvotes: 0
Views: 70
Reputation: 45252
This is the programming paradigm that every new javascript developer has to deal with.
Because of the asynchronous nature of javascript, functions tend not to pass values back via return
statements, but instead the values are passed back via callback methods.
function something(url) {
getPage(url, function(temp) {
console.log(temp);
});
}
function getPage(url, callback) {
var x = new XMLHTTPRequest();
x.onload = function() {
var html = x.responseText;
//CODE TO PARSE HTML TEXT
var variable = SOMETHING PARSED FROM HTML
callback(variable);
}
x.open("GET", url);
x.send();
}
Upvotes: 1