0

Please I need help ! To begin I don't speaking very well english sorry for the mistakes

So I'm tryng to receive a JSON Object with this code :

function uhttp(url){
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
        var status = xhr.status;
        if (status == 200) {
            console.log(xhr.response)
            return xhr.response;
        } 
    };
    xhr.send();
    console.log('exit')
};

but when I use the function https like this :

`

 ( ()=>{
    var perso =uhttp('bd.php?table=charac')

    for (var i = 0; i < perso.lenght; i++) {
        document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>')
    }
})()

` perso he's undifined... here the console of index.html

I've the impression that we'are exit the function before that whe receive the resonse and that is why the function return a null Of course before to ask my question I'have make some research but no one working in my case.... Thank you for yours anwsers

Antoine Guil
  • 21
  • 1
  • 3
  • Possible duplicate of [How to return value from an asynchronous callback function?](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Mikey May 25 '18 at 20:30

1 Answers1

0

It happens because you aren't returning value from uhttp() function but from anonymous function (xhr.onload).

In order to access this value after the AJAX call is over use promises:

function uhttp(url){
    return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        resolve(xhr.response);
        return;
      } 

      reject();
    };

    xhr.onerror = function() {
        reject()
    };

    xhr.send();
  })
}

And use it like so:

uhttp('bd.php?table=charac').then(function(result) {
    var person = result;
    for (var i = 0; i < perso.lenght; i++) {
        document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>');
    }
  }).catch(function() {
   // Logic on error
  });
user3210641
  • 1,565
  • 1
  • 10
  • 14