Search code examples
javascriptphpxmlhttprequest

Can't retrieve element from array using XMLHttpRequest


Can't access elements in array from XMLHttpRequest.

I have a function called findProductDetails where i pass in a productName which is a primary key in my database. I use XMLHttpRequest to retrieve the array through a response from productSearch.php . I can print itemsList perfectly inside the for loop. But I tried returning the array, and i can print it to console and it will show that it has a length of 0 and I can see the elements, but cannot retrieve them individually as array[n].

 function findProductDetails(productName){
      //Store results      
      var array = []

      xmlhttp=new XMLHttpRequest();
      xmlhttp.onreadystatechange=function() {

           if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                if (xmlhttp.responseText) {
                    var itemsList = xmlhttp.responseText.split(",");
                    for(var i = 0; i < itemsList.length; i++) {
                        array[i] = itemsList[i];
                    }        
                }
           }
      }

      xmlhttp.open("GET","productSearch.php?name=" + productName,true);
      xmlhttp.send();

      return array;
  }

What's going on?


Solution

  • My Solution:

    function request(method, url) {
         return new Promise(function (resolve, reject) {
               var xhr = new XMLHttpRequest();
               xhr.open(method, url);
               xhr.onload = resolve;
               xhr.onerror = reject;
               xhr.send();
         });
    }
    

    Then I called this whenever I wanted to retrieve data from database through php file by echoing the results.

     request("GET", "productSearch.php?name=" + productName,true)
           .then(function (e) {
                //Results      
                var res = e.target.response;
    
            }, function (e) {
              // handle errors
        });