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