Search code examples
jqueryfile-exists

href depending on ajax success or fail


In my Wordpress, I have custom attachment sizes set at 128x79 and 896x277. My images will for sure be larger than 128x79. If the image is smaller than 896x277, it crops off whatever is larger than the max size and sets the other to its max. Meaning an image of 500x300 will be cropped to 500x277.

Lets say on my page I have an image with href http://domain.com/files-128x79.jpg and I want to replace files-128x79.jpg with files-896x277.jpg if it exists, otherwise, find the largest image with height as priority.

Ok... I've decided to simplify my problem to make it easier. All I'm doing now is to check if files-896x277.jpg exists and if not, I want it to output files.jpg instead. I've got this so far, but can't seem to set the anchor href.

$rewrite.find('a').each(function(index, element) {
    $.ajax({
        url : $(this).children().attr('src').replace('-128x79.', '-896x277.'),
        type: 'head',
        success : function() {
                $(this).attr('href', $(this).children().attr('src').replace('-128x79.', '-896x277.'));
        },
        error : function(xhr, d, e) {
            if (xhr.status == 404) {
                $(this).attr('href', $(this).children().attr('src').replace('-128x79.', '.'));
            }
        }
    });
});

What am I doing wrong?


Solution

  • Inside the AJAX callback, what is in this? Is it still the element which caused the event? If so, which event? The AJAX result event?

    I suggest to save this to a local variable to make sure it contains what you expect:

    $(function () {
        var that = $(this);
        $.ajax({
        url : that.children()....