Reputation: 1
This script uses an API to access information from a database and displays a 'spotlight' for a random person in the db that includes their name, a photo, and a short bio.
I'm trying to write this script to check if the image exists. If the image exists, then the script should continue, but if the image doesn't exists (404 error) it should reroll and check again. I'm having issues understanding how to work with the asynchronous part of ajax.
function checkImage(imgurl){
function headRequest(url){
return $.ajax({ //Makes a HEAD request for the image
url: url,
type: 'HEAD'
});
};
headRequest(imgurl)
.done(function(){
return true; //image exists
})
.fail(function(){
return false; //HEAD request returns 404
});
};
//if image does not exist or person.biography is undefined, reroll
while (!checkImage(imgsrc) || person.biography == undefined) {
//select random person
}
Upvotes: 0
Views: 816
Reputation: 1
So I ended up setting the asynchronous portion to false. I know it's not good practice, but this is the best solution for the interim.
function checkImage(imgurl){
function headRequest(url){
var http = $.ajax({
url: url,
type: "HEAD",
async: false
})
return http.status;
}
if(headRequest(imgurl) == 200) {
return true;
}
else {
return false;
}
}
//if image does not exist or person.biography is undefined, reroll
while (!checkImage(imgsrc) || person.biography == undefined) {
//reroll
}
Upvotes: 0
Reputation: 1433
function checkImage(imgurl, callback){
function headRequest(url){
return $.ajax({
url: url,
type: 'HEAD'
});
};
headRequest(imgurl)
.done(function(){
//Do whatever you wanted to do after it successfully found
callback(imgurl);
})
.fail(function(){
var newRandom = GetNewRandom(): //get your new random person url
checkImage(newRandom, callback); //Try again
});
};
So this way it keep iterating through calls until it locates a match. For example, maybe it would be run like this:
var firstPerson = GetNewRandom(); //Initial person
function myCallback(url) {
$('#myImage').attr('src', url); //Change src to successful image
}
checkImage(firstPerson, myCallback); //starting with this person, look for a match
Upvotes: 0
Reputation: 104775
Got to use a callback! (You can't return from an async
call)
function checkImage(imgurl, callback){
function headRequest(url){
return $.ajax({ //Makes a HEAD request for the image
url: url,
type: 'HEAD'
});
};
headRequest(imgurl)
.done(function(){
callback(true); //image exists
})
.fail(function(){
callback(false); //HEAD request returns 404
});
};
And call the function:
checkImage(imgsrc, function(exists) {
//exists is what you passed into the callback
if (exists) { //do stuff
} else {
//doesnt
}
});
Upvotes: 2