-1

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?

fent00
  • 31
  • 7
  • Can you console.log responseText? – Elanochecer Apr 11 '19 at 14:00
  • Possible duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – 04FS Apr 11 '19 at 14:03
  • @Elanochecer From `console.log(xmlhttp.responseText.split(","));` it prints what I want, an array with a length of 4 elements. – fent00 Apr 11 '19 at 14:05
  • 1
    Oh you cant do that you are returning the array before the response arrives. Turn the function into a promise. The easiest way is to just use jquery ajax function. http://api.jquery.com/jquery.ajax/ – Elanochecer Apr 11 '19 at 14:10
  • @Elanochecer Thank you! Got it to work. – fent00 Apr 11 '19 at 14:47

1 Answers1

0

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
    });
fent00
  • 31
  • 7