0

hi guys I have this function: its checking if the image URL is an actual image, but I want to change it , instead of console log I want it to return true or false,

function checkImage(url) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.send();
  request.onload = function() {
    status = request.status;
    if (request.status == 200) //if(statusText == OK)
    {
      console.log("image exists");
    } else {
      console.log("image doesn't exist");
    }
  }
}
checkImage("https://picsum.photos/200/300");

I want checkImage to return True/False instead of console logging, but when i write return true or false, that doesn't seem to work, anyone knows why?

Eddie
  • 26,593
  • 6
  • 36
  • 58
Alexander
  • 1,288
  • 5
  • 19
  • 38
  • 1
    The `.onload` function won't actually be called until the HTTP request completes, and that will be long after `checkImage()` has returned. – Pointy Apr 27 '19 at 13:31
  • 1
    so I should do it async? – Alexander Apr 27 '19 at 13:34
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hacketo Apr 27 '19 at 13:34
  • In what context are you trying to use the checkImage function? – Tekill Apr 27 '19 at 13:37
  • @Tekill I'm making a website when users can add an image to their profile, I want to check if the image exists and then show it or put a default picture if it doesnt. – Alexander Apr 27 '19 at 13:38
  • Why can't you just return true and return false instead of the console.log() and store the checkImage function result into a variable or check it inside a if statement. – RonnyRules Apr 27 '19 at 13:39
  • @RonnyRules Check the possible duplicate (and the other question mentioned in the accepted answer) for the answer. – Andreas Apr 27 '19 at 13:42
  • @RonnyRules I tried that, didn't work – Alexander Apr 27 '19 at 13:43
  • @AlexK it already is asynchronous. – Pointy Apr 27 '19 at 13:43
  • @Andreas If I insert a "https:google.com" URL, will the image exist aswell? – Alexander Apr 27 '19 at 13:44

2 Answers2

3

If the whole purpose of this function is to check if the image exists with the intent of displaying a default image I would use a much simpler approach. Why not use the following method:

<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />

This is described at further length here

Tekill
  • 1,171
  • 1
  • 14
  • 30
2

Just change the console to callback may help u solve it

function checkImg(url,success,error){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send();
request.onload = function() {
status = request.status;
if (request.status == 200) //.if(statusText == OK)
{
  success && success()
} else {
  error && error()
}

} }

Replace the Ajax with Image.onload()

fbfatboy
  • 371
  • 1
  • 6