Paul Aston
Paul Aston

Reputation: 135

jQuery, Check if image exists returns false negative

I'm trying to determine if an image exists before inserting it into the site.

I've tried all the methods here and all of them return a negative for an image I know exists. For example:

$.ajax({
url:'https://s3-eu-west-1.amazonaws.com/stuffstory-v2-filepicker/thumbnails/5547b98e357a7f425f8b4570/555340a1357a7f673a8b456b.png',
type:'HEAD',
error:
    function(){
        console.log('No image')
    },
success:
    function(){
        console.log('There is an image')
    }
});

Returns a no image result, but when if you follow the link: Image It's clearly there.

I am utterly flummoxed as to why.

Upvotes: 1

Views: 773

Answers (6)

Jamin Lin
Jamin Lin

Reputation: 1

You can do this :

$(function () {
   //Image Error
   $("img").on("error", function () {
     var $img = $(this);
     var imgsrc = $img.attr("src");
     $img.attr("src", "New Image Path");
   });
});

Upvotes: 0

Rakesh Garg
Rakesh Garg

Reputation: 27

You can use jsonp requests to load cross domain resources for example image in your case

Upvotes: 0

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 21

You are calling a request that is on different domain from your app thats why it is restricting this. if you will open your console window you will see the error. you need to achieve this using cors. reference http://www.html5rocks.com/en/tutorials/cors/

Upvotes: 0

Shimon Rachlenko
Shimon Rachlenko

Reputation: 5517

You can use the Image for this:

var imageUrl = 'https://s3-eu-west-1.amazonaws.com/stuffstory-v2-filepicker/thumbnails/5547b98e357a7f425f8b4570/555340a1357a7f673a8b456b.png';
var img = new Image();
img.onload = function(){
    // will be called if image exists
};
img.onerror = function (){
   // will be called if image failed to download
};
img.src = imageUrl;

This way the images can be downloaded cross-domain. See also Image on MDN.

Upvotes: 3

imbondbaby
imbondbaby

Reputation: 6411

As stated by @crashet

No 'Access-Control-Allow-Origin' header is present on the requested resource.

For an alternative:

Use onerror Event

Execute a JavaScript if an error occurs when loading an image:

HTML:

<img src="https://s3-eu-west-1.amazonaws.com/stuffstory-v2-filepicker/thumbnails/5547b98e357a7f425f8b4570/555340a1357a7f673a8b456bewweweg" onerror="imgError()" />

JS:

function imgError()
{
alert('The image could not be loaded.');
}

JSFiddle Demo

More info: http://www.w3schools.com/jsref/event_onerror.asp

Upvotes: 0

Serge K
Serge K

Reputation: 375

Your cross-domain AJAX request is blocked by CORS security policy:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Upvotes: 4

Related Questions