Search code examples
javascriptajaxxmlhttprequest

Function returns undefined in Javascript


Can not figure it out how to return value (string) from this function:

function loadPage(url) {
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", url, true);
    xhttp.send();

    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            //var html = xhttp.responseText
            var html = document.documentElement.outerHTML;
            return html
        }
    }
}

console.log(loadPage("http://stops.lt/vilnius/#trol/2/a-b"))

When I use console.log(html) inside xhttp.onreadystatechange it prints correct results, but I don't understand how to return loadPage(url). Tried both return xhttp.onreadystatechange and return xhttp.onreadystatechange() and none of these works.


Solution

  • Fuction loadPage is async, you need to use callback function(or Promise):

    function loadPage(url, cb) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", url, true);
        xhttp.send();
    
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                //var html = xhttp.responseText
                var html = document.documentElement.outerHTML;
                cb(html);
            }
        }
    }
    loadPage("http://stops.lt/vilnius/#trol/2/a-b", function(html){
        console.log(html);
    });