0

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();
}

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

If I need multiple call backs like multiple functions that use XMLHTTPRequest after one another, would I just do the same "callback" for each function?
for example... somefunction(url, function(res) { callback(res); });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.