I'm grappling with the effectiveness of my ajax implementation as I cycle through an array of data using a for loop:
loadProfiles.js
var tempString = "";
var searchPeople = function(sv){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
tempString = xhttp.responseText;
loadPeople(tempString, sv);
}
}
var searchvalue = sv;
searchvalue = searchvalue.join(" ");
xhttp.open("GET", "php/searchProfiles.php?searchvalue=" + searchvalue, true);
xhttp.send();
}
var loadPeople = function(people, sv){
loadedPeople = [];
var normList = people.split(",");
var list = people.toLowerCase().split(",");
list.splice(list.length - 1, 1);
var zsearch = sv;
for(var i = 0; i < list.length; i++){
loadedImageId[i] = list[i].split("_")[1];
if(loadedImageId[i] == 0){
loadedImageId[i] = "images/GrayProfilePic.png";
}
else{///////////////////////////////////This is what I need to fix
var grabPic = new XMLHttpRequest();
grabPic.onreadystatechange = function(){
if(grabPic.readyState == 4 && grabPic.status == 200){
console.log("ready to go");
loadedImageId[i] = grabPic.responseText;
if(loadedImageId[i] == "Error1"){
loadedImageId[i] = "images/GrayProfilePic.png";
}
}
}
grabPic.open("GET", "php/grabProfPics.php?imageid=" + loadedImageId[i], true);
grabPic.send();
}//////////////////////////////////////////////
list[i] = list[i].split("_")[0];
for(var j = 0; j < zsearch.length; j++){
if(list[i].indexOf(zsearch[j]) > -1){
if(loadedPeople.indexOf(list[i]) == -1){
if(loadedPeople.indexOf(normList[i].split("_")[0]) == -1){
loadedPeople.push(normList[i].split("_")[0]);
}
}
}
}
}
console.log(loadedPeople);
console.log(loadedImageId);
}
searchProfiles.php
$query = "SELECT username, imageid FROM `memberHandler`";
$result = mysqli_query($connect, $query) or die("Could not query");
while($row = mysqli_fetch_assoc($result)){
echo $row['username'] . "_" . $row['imageid'] . ",";
}
grabProfPics.php
$query = "SELECT image, mime_type FROM memberProfilePictures WHERE `id`='$imageid'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) != 0){
$row = mysqli_fetch_assoc($result);
$imagesrc = $row['image'];
$imagesrc = base64_encode($imagesrc);
$imagetype = $row['mime_type'];
echo "data:" . $imagetype . ";base64," . $imagesrc . "";
}
else{
echo "Error1";
}
One issue I'm facing is that the server's response time can cause the for loop iteration variable 'i' to be different by the time the callback is executed. Is there a more efficient way to handle this and dynamically update the array based on its current value? Thank you for any insights =)
In essence, I'm attempting to iterate over image IDs and if it's non-zero (indicating they have a profile image set), then making an ajax request to fetch the corresponding image from a database. Subsequently, updating the array with the retrieved image source. Apologies for any earlier ambiguity in my explanation.