Use jQuery to check if links still work
ajax, http-status-code-404, javascript, jquery
Solution
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.
Problem
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') }) }) }); ```