0

I have a function which makes an ajax request (see code below), how do I return the response?

Code:

const ajaxreq = (url) => {
    let xhttp = new XMLHttpRequest();
    let res = "";
    xhttp.onreadystatechange = _ => {
      if (this.readyState === 4) {
        res = this.responseText
      }
    };
    xhttp.open("GET", url, true);
    xhttp.send();
}

I have tried placing the return statment inside the xhttp.onreadystatechange, but this doesn't make the function ajaxreq return that value, only the anonymous function. If I place the return statement after xhttp.send();, then the request doesn't have enough time to fulfill and the function just returns an empty string.

How can I solve this problem?

Emil E. Ohman
  • 153
  • 2
  • 11
  • The reason why it is not working is that the function completes long before the request is answered, I would look into using an async function. – Ben Jul 12 '19 at 15:27
  • It looks like maybe you are trying to call an async method in a synchronous manner. If you want to call a function and have it return the results of an ajax call, that ajax call will need to by synchronous. – Seano666 Jul 12 '19 at 15:28
  • @Seano666 but synchronous xhr requests are a terrible practice since they block the whole UI and are deprecated by browser vendors. Not a best practice suggestion – charlietfl Jul 12 '19 at 15:32
  • @charlietfl Agreed, I wasn't trying to address best practices but just trying to reframe his issue so he can understand it better. – Seano666 Jul 12 '19 at 15:36
  • @Seano666 What is a better practice? – Emil E. Ohman Jul 12 '19 at 15:55

0 Answers0