Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to check if links still work

I made a quick function to check every link on the page using AJAX to see if they still work. This seems to be working, but it's adding the success and error class to every one. How can I get the error callback function to only throw if the AJAX response is 404?

$('li').each(function(){
    $(this).children('a').each(function(){
        $.ajax({
            url:$(this).attr('src'),
            success:$(this).addClass('success'),
            error:$(this).addClass('error')
        })
    })
});
like image 382
Throttlehead Avatar asked Nov 09 '12 14:11

Throttlehead


2 Answers

the success and error parameters expect functions.

You'd need to wrap the code in an anonymous function:

//there's no need to complicate things, use one call to each()
$('li > a').each(function () {
    var $this;
    $this = $(this); //retain a reference to the current link
    $.ajax({
        url:$(this).attr('href'), //be sure to check the right attribute
        success: function () { //pass an anonymous callback function
            $this.addClass('success');
        },
        error: function (jqXHR, status, er) {
            //only set the error on 404
            if (jqXHR.status === 404) { 
                $this.addClass('error');
            }
            //you could perform additional checking with different classes
            //for other 400 and 500 level HTTP status codes.
        }
    });
});

Otherwise, you're just setting success to the return value of $(this).addClass('success');, which is just a jQuery collection.

like image 177
zzzzBov Avatar answered Oct 21 '22 03:10

zzzzBov


First you need a success and failed handler, now the code just runs for every link. You don't need the src attribute, but the href prop.

This should work:

$('li').each(function(){
   $(this).children('a').each(function(){
    $.ajax({
        url:$(this).prop('href'),
        success:function(){$(this).addClass('success')},
        error:function(){$(this).addClass('error')}
    })
  })
});

I also find it more elegant to use index and value in the each loop, so:

$('li').each(function(){
   $(this).children('a').each(function(index,value){
    $.ajax({
        url:$(value).prop('href'),
        success:function(){$(value).addClass('success')},
        error:function(){$(value).addClass('error')}
    })
  })
});
like image 1
Ruben-J Avatar answered Oct 21 '22 03:10

Ruben-J