Search code examples
javascriptjsonxmlhttprequestvarscoping

How to access XMLHttpRequest values outside the onreadystatechange function


i have a .php file that outputs a json data, which it does perfectly and i get this results:

[
{
    "name": "ADMINISTRATOR",
    "email": "",
    "first_name": "",
    "last_name": ""
},
{
    "name": "GUEST",
    "email": "",
    "first_name": "",
    "last_name": ""
},
{
    "name": "KRBTGT",
    "email": "",
    "first_name": "",
    "last_name": ""
},
{
    "name": "DIMERS",
    "email": "",
    "first_name": "Dimers",
    "last_name": "David"
}
]

i also have a .js file which calls this results using XMLHttpRequest like so:

function loadDoc() {
 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) 
    {

        var contact = JSON.parse(this.responseText);

              for (var i = 0; i < contact.length; i++) 
            {
                var contacts = {name: contact[i].name, email: contact[i].email, 
                 Govphone: contact[i].first_name, phone: contact[i].last_name};

                console.log(contacts);

            }


       }
    };
  xhttp.open("GET", "js/contalist.php", true);

  xhttp.send();

  }

  loadDoc();

in console i'm able to get the contacts. but i need to assign the value from the response to a variable outside of the call, like so

 .factory('ContactService', [function () {
    var factory = {};

    factory.getContacts = function (response) {

    var contactsList=contacts;
    return contactsList;

   };

   return factory;
  }]);

Can someone help me on how I can at least extract the contents in the contacts variable so that i can use it else where within the code?


Solution

  • You can push the responseText and have it available elsewhere in the scope.

    var theContacts=[];
    function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                theContacts.push(this.responseText);
            }
            xhttp.open("GET", "js/contalist.php", true);
            xhttp.send();
        }
    }
    
    loadDoc();
    
    
    .factory('ContactService', [function() {
        var factory = {};
    
        factory.getContacts = function(response) {
    
            var contactsList=theContacts;
            return contactsList;
        };
    
        return factory;
    }]);
    

    To get a flattened array:

    theContacts.flat();