1

In JS, I wanted to create a function that made a xHTMLRequest to a backend PHP server, problem is I want JS to wait for the response, otherwise it will display 'undefined'.

function xhrReq(method, args) {
let xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(args);
xhr.onreadystatechange = ()=> {
    if(xhr.readyState == 4) {
        return xhr.response;
    }
}

How can I make this function return the response value?

2
  • 1
    onreadystatechange will be called when the request has a final state, like 404, 200, 301 ecc ecc, so already you are qaiting for the response... Commented Dec 3, 2019 at 22:13
  • You don't return the response. Instead, you perform the action you want within the statechange callback. Commented Dec 3, 2019 at 22:28

1 Answer 1

1

You can use fetch in a async function:

(async () => {
  try {
    //const args = ...;
    var headers = new Headers();
    headers.append("Content-Type", "application/x-www-form-urlencoded");
    const response = await fetch('http://localhost/example/php/example.php', {
      method: 'POST', // or other
      headers,
      body: args
    });
  } catch (err) {
    //process error
  }
})()

or you can promisify your function :

function xhrReq(method, args) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, 'http://localhost/example/php/example.php');
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onload = function() {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(Error(`XHR request failed. Error code: ${xhr.statusText}`));
      }
    };
    xhr.onerror = function() {
      reject(Error('There was a network error.'));
    };
    xhr.send(args);
  });
}

And use it in a async function (or use promise) to get the response.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that helped, I got it to work with promises, but now that you mentioned, I'm actually keen in researching more about fetch API

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.