tags:

views:

20

answers:

1

This function everytime gives "false", even if image_url exists

// some .each {
    var item = $('.item', this);
    $.ajax({
        url: image_url,
        success: function() {
            item.html("true");
        },
        error: function() {
            item.html("false");
        }
    });
// }

Its used to check existance of image_url file - this variable gives url like http://blog.com/teddybear.png

Any idea?

+2  A: 

You can't do something like this due to the same-origin policy which prevents fetching any data from another domain.

However, there is hope! You can use the error event for an <img> element to see if it exists, like this:

function testImage(url) {
    $("<img />", { 
      error: function() { item.html('false'); }, 
      load: function() { item.html('true'); }
    })​​.attr('src', url);
}

You can view a quick demo here, it tests for an image that does exist, waits 2 seconds then tries one that doesn't. This uses the $(html, props) creation method to create a <img> element, assign events, then set the src, we're just checking which event gets hit as the pass/fail check.

Nick Craver
I call this function with testImage(result);
Happy
result is an url
Happy
this doesn't work - load: function() { item.html('<img src="' + result + '"/>'); }
Happy
@Happy - No need to load it again, you already have the image, you can do `item.empty().append(this);`, like this: http://jsfiddle.net/cKKTe/
Nick Craver
Please give some ability to use code like this load: function() { item.html('<img src="' + result + '"/>'); }
Happy
I have to throw var result to <img src, else { throw another var }
Happy
@Happy - It's an synchronous check, so you can't return a variable here, you can call another function *from* the `load` function, but you can't return anything...this is just how asynchronous things work. This is exactly your code: http://jsfiddle.net/cKKTe/1/ , what trouble are you having with it?
Nick Craver
its ok now, thanks for solution.
Happy