Detect Image Loading Error with jQuery

The following JavaScript code shows how to detect image loading error using jQuery. It uses bind to attach a handler to the “error” event for all image elements.

jQuery('img').bind('error', function (e) {
    console.log('image error: ' + this.src);

Using ajax, we can log or handle such events. Suppose we have an “image” table and we would like to delete images that are not loaded correctly. The client-side JavaScript code extends the above example by issuing an ajax request (together with the image url).

jQuery('img').bind('error', function (e) {
    var src = this.src;
        url: '/delete_img.php',
        data: {src: src}

For the server side, we create a PHP file “delete_img.php” to delete images with loading error.

$src = $_GET['src'];

// connect database

$query = "delete from image where url = '$src' ";


Related Posts




Posted in JavaScript