Search code examples
javascripthttprequest

Value of Async Function or Value of HTTP Request


Good evening,

Im quite new in JavaScript. I want to get the innerhtml with XMLHttpRequest. The main code works, if I just print the result with console.log - I see what I want, but I dont know how to save it as a string, cause I need to work with it. Can you help me out please.

My Code:

function getBasketCode(){
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = async function () {
        if (xhr.readyState == xhr.DONE) {
            //var code = xhr.responseText;
            var code = document.getElementById("shoppingcart_filled").innerHTML;
            console.log(code); // <-- here it shows me the right result
        }
    }
    xhr.open('GET', 'https://www.xxxxx.nl/xxxx', true);
    xhr.send();
}
getBasketCode();

Solution

  • function getBasketCode() {
      return new Promise((resolve) => {
        var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = async function () {
          if (xhr.readyState == xhr.DONE) {
            var code = document.getElementById("shoppingcart_filled").innerHTML;
            resolve(code);
          }
        }
        xhr.open('GET', 'https://www.xxxxx.nl/xxxx', true);
        xhr.send();
      });
    }
    const code = await getBasketCode(); // assuming you are in an async function, otherwise getBasketCode().then((code) => {...