javascript - Check if image exists via jquery ajax? -


this script uses api access information database , displays 'spotlight' random person in db includes name, photo, , short bio.

i'm trying write script check if image exists. if image exists, script should continue, if image doesn't exists (404 error) should reroll , check again. i'm having issues understanding how work asynchronous part of ajax.

        function checkimage(imgurl){            function headrequest(url){                return $.ajax({  //makes head request image                    url: url,                    type: 'head'                });             };             headrequest(imgurl)             .done(function(){                 return true; //image exists              })             .fail(function(){                 return false; //head request returns 404              });         };      //if image not exist or person.biography undefined, reroll     while (!checkimage(imgsrc) || person.biography == undefined) {         //select random person     } 

got use callback! (you can't return async call)

function checkimage(imgurl, callback){        function headrequest(url){            return $.ajax({  //makes head request image                url: url,                type: 'head'            });         };         headrequest(imgurl)         .done(function(){             callback(true); //image exists          })         .fail(function(){             callback(false); //head request returns 404          });  }; 

and call function:

checkimage(imgsrc, function(exists) {     //exists passed callback     if (exists) { //do stuff      } else {         //doesnt     } }); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

jquery - Keeping Kendo Datepicker in min/max range -