0

I have a XMLHttpRequest in a function, and the result work fine. but i can't return this value.

plugin.js

var users = getUsers(url);

pluginfunctions.js

function getUsers(u) {

var obRespuesta = [];

  var client = new XMLHttpRequest();
  client.onreadystatechange = function() {
    if (client.readyState == XMLHttpRequest.DONE) {

      obRespuesta = JSON.parse(client.responseText);
      console.log(obRespuesta);
          }
  };

  client.open("GET", "http://localhost/extencio/index.php?url=" + u, true);
  client.send();

console.log(obRespuesta);
return obRespuesta;

}

Ok, obRespuesta is an empty array. The value of the first console.log is: array[2]. it works well.

But the value of the last console.log and the return, is an empty array. array[0]

I think it is because the return is executed before than client change state.

how do I solve it?

Phyron
  • 613
  • 1
  • 9
  • 25

1 Answers1

1

You need to have your function accept a callback and invoke that callback instead.

function getUsers(u, callback) {
    var obRespuesta = [];

    var client = new XMLHttpRequest();
    client.onreadystatechange = function() {
        if (client.readyState == XMLHttpRequest.DONE) {
            obRespuesta = JSON.parse(client.responseText);
            callback(obRespuesta);
        }
    };

    client.open("GET", "http://localhost/extencio/index.php?url=" + u, true);
    client.send();
}

So now you get your users via:

getUsers(url, function(users) {
    //do your parsing with users
});
Dave Chen
  • 10,887
  • 8
  • 39
  • 67