0

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();
Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
Mahal
  • 7
  • 2
  • 1. have you tried setting it under the `window` object? 2. It looks like, if the `shoppingcart_filled` is updated regardless the request, you still directly use from there any time you wish? – Aziza Kasenova Aug 24 '21 at 23:37
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – tevemadar Aug 24 '21 at 23:48

1 Answers1

1
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) => {...
see sharper
  • 11,505
  • 8
  • 46
  • 65
  • it works, thank you very much, could you please explain your last comment "getBasketCode().then((code) => {..." for what do i need .then method in a non async function – Mahal Aug 25 '21 at 10:00
  • You can only use the await keyword in a functin that is marked `async`. If for some reason you can't do that (there are reasons), or you are in the root scope (not inside a function), then you would need to use the .then syntax instead. – see sharper Aug 25 '21 at 23:55
  • As this answered your question, please don't forget to mark as answer by clicking the tick on the left (and upvoting, if you like). – see sharper Aug 25 '21 at 23:56