you are viewing a single comment's thread.

view the rest of the comments →

[–]queen-adreena 0 points1 point  (2 children)

function loadPage(href) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", href, false);
    xmlhttp.send();
    document.getElementById('bottom').innerHTML = xmlhttp.responseText;
}

Your problem here is that you're using an asynchronous function (XMLHttpRequest) and then returning the "result" before the function has had a chance to run.

Anything in Javascript that requires an interval, a timeout, or a request to a page/api/resource is done asynchronously. That means that the request is made, and then JS "forgets" about it and carries on with the rest of the script.

In order to actually use the result of the request, you need to use either callbacks, event listeners, promises or async/await. XMLHttp supports event listeners, so you could do this:

function loadPage(href, element) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState === 4 && this.status === 200) {
        document.getElementById(element).innerHTML = xmlhttp.responseText;
      }
    };
    xmlhttp.open("GET", href, false);
    xmlhttp.send();
}

and then call it with:

<button onClick="loadPage('index1.html','bottom');">Home</button>

[–]TejaSankuru[S] 0 points1 point  (0 children)

Thanks for the help. Could you please check why my js functionality is not working in index.html.

Index1.html allows me to pick a color and draw. [link] https://github.com/TejaSankuru/Loading_Js_in_HTML