A
A
Alexander Degtyarev2018-03-06 11:27:30
JavaScript
Alexander Degtyarev, 2018-03-06 11:27:30

Why is it throwing undefined inside XMLHttpRequest?

function get_manager(manager_id) {
    var xhr_one = new XMLHttpRequest();
    var name_manager = '';

    xhr_one.open('get', 'http://localhost:8000/get_managers?mid=' + manager_id + '&secure=' + localStorage.getItem('secure'), true);
    xhr_one.send();

    xhr_one.addEventListener('load', function () {
        name_manager = JSON.parse(xhr_one.response);

        return name_manager.fullname;
    });
}

Why does it return undefined? If you put return outside, then nothing is displayed at all

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Kalibrov, 2018-03-06
@alexdeg

You can make the get_manager function return a promise:

function get_manager(manager_id) {
  return new Promise(function (resolve, reject) {
    var xhr_one = new XMLHttpRequest();
    var name_manager = '';

    xhr_one.open('get', 'http://localhost:8000/get_managers?mid=' + manager_id + '&secure=' + localStorage.getItem('secure'), true);
    xhr_one.send();

    xhr_one.addEventListener('load', function () {
        name_manager = JSON.parse(xhr_one.response);
        resolve(name_manager.fullname);
    });
    
    xhr_one.addEventListener('error', function () {
      reject({
        status: this.status,
        statusText: xhr_one.statusText
      });
    });
  }
}

call it like this:
get_manager(manager_id).then((name_manager) => {
  console.log(name_manager);
});

R
Rsa97, 2018-03-06
@Rsa97

And where should return return the response if the function fires asynchronously, after the response from the server arrives?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question