Ajax - Function to check if Url exists

Simon Be picture Simon Be · Feb 8, 2013 · Viewed 21.3k times · Source

I'm building a building a website using the Reddit API to display images from Reddit. I'm getting the data via JSON then use it to build the page, using URLs provided as sources for the images.

Some of the URLs that I get don't go to images directly, but instead to image hosting sites (like imgur.com). Usually, adding '.jpg' at the end of the URL takes me to the right image.

So, doing that, I would like to check if the URL + '.jpg' exists before using it.

I tried to build a function to check the url.

function checkUrl(url){
    var request = new XMLHttpRequest;
    request.open('GET', url, true);
    request.send();
    request.onreadystatechange = function(){
        if(request.readyState==4){
            console.log(request.readyState);
            return true;
        }else{
            return false;
        }
    }
};

//Then I use the function to check and append the data to the page
var url = url+'.jpg';
if(checkUrl(url)){
    //work with the data
}else{
    //do nothing
}

Nothing happens to the page, still I get the readyState logged into the console, so the checkUrl() function seems to be returning true.

What I am doing wrong ? I am pretty new to the whole Ajax thing, so some help would very appreciated.

Thank you

Answer

joeltine picture joeltine · Feb 8, 2013

Your problem is that when request.readyState == 4 this means the request has completed, regardless of what the result of that request was. So even if the URL you request returns a "404 not found", you'll still see the XHR resolving itself to readyState 4.

To address what you're trying to do, I'd recommend checking the status code of the response. For example, using your code:

if(request.status==200){
   return true;
}