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?