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')
})
})
});
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.
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')}
})
})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With