0

I have detected broken images and getting broken src's and store them into the object but unable to store them into an object because of I think there is a time difference between error function and catching them into object please check my code.

I successfully get src but unable to store them in object variable and passing them into backend via ajax. By debugging testing it I think

brokenImages.current_url = currentUrl;  
brokenImages.broken_src = brokenSrc;

Run before error function and I get nothing in brokenImages variable.

jQuery(document).ready(function($){

        //Check Image Error
        var i = 0;
        var currentUrl = window.location.href;
        var brokenImages = new Object();
        var brokenSrc = new Object();


        $('img').on('error', function(event){

            var link = event.target.src;

            console.log('check '+link + ' num ' + i);

            brokenSrc[i] = link;

            i++;
        });

        //alert(brokenSrc);

        //Like if I put alert brokenSrc object here I get them in ajax and php

        console.log(' broken src ');
        console.log(brokenSrc);

        brokenImages.current_url = currentUrl;  
        brokenImages.broken_src = brokenSrc;

        console.log( ' broken images ' );
        console.log(brokenImages);

//In console log of chrome and firefox I can see object and srcs in them but when ajax sending them and catching them into php there is nothing broken_src

        //Sent Script Data
        $.ajax({
            type: "POST",
            url: ajax_url,
            data: {
                imageData: brokenImages
            },
            success: function(result){
                console.log(result);
            }
        });

});

Unable to store them in brokenImages variables while successfully getting them.

2
  • api.jquery.com/error Are you asking how to fix the error() call without checking the docs first? That's really not how stackoverflow works. Asking a question should be the absolute last resort. jsfiddle.net/4n3f3sbr/1 Commented May 15, 2018 at 11:10
  • @ChrisG no I am not asking this error function is running and I am getting error successfully but unable to get into object and pass them into backend because assigning them into object run before error function. Kindly help Commented May 15, 2018 at 11:25

2 Answers 2

3

.error is deprecated, need to use .on('event' instead.

Allow error is asynchronous, your code is not waiting for images to get loaded to send final report of broken images. Also empty src attribute on img will not trigger error or success, you need to ignore or add them separately. I have ignored them in below code.

$(document).ready(function() {

    //Check Image Error
    var i = 0;
    var brokenSrc = [];

    var totalImagesOnPage = $('img').not( "[src='']" ).length;

    $('img').on('load', function() {
        increaseCount();
    }).on('error', function() {
        var link = $(this).attr('src');
        console.log('broken link : ' + link);
        brokenSrc.push(link);
        increaseCount();
    });


    function increaseCount() {
        i++;
        if (i == totalImagesOnPage) {
            finishedLoadingImages();
        }
    }

    function finishedLoadingImages() {
        console.log("Broken images ::", brokenSrc);
        $.ajax({
            type: "POST",
            url: '/',
            data: {
                imageData: {
                    current_url: window.location.href,
                    broken_src: brokenSrc
                }
            },
            success: function(result) {
                console.log(result);
            }
        });
    }

});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>


<img src="" />
<img src="http://google.com" />
<img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2014/05/1399880336proe-pic_400x400-96x96.jpg" />
<img src="https://simplyaccessible.com/wordpress/wp-content/themes/sa-wp-2014/images/logo.svg"/>

 </body>
</html>

Sign up to request clarification or add additional context in comments.

8 Comments

here is the jsbin link for working code jsbin.com/cizetovuvo/2/edit?html,js,console,output
Thank you so much @Shivaji Varma but one problem facing on('load') not running and not increaseCount in chrome but in firefox it is running.
which version of chrome are you using? because i'm using chrome, it worked.
Version 66.0.3359.139
|
0

The reason that $('img').error throws an exception is that $('img').error is really not a function. However, if you want to catch failures on image loading you can use onerror like this:

$(function(){
  var error_object_array = [];
  $('img').on('error', function(event) {
    error_object_array.push(event.target.src);
  });
})

5 Comments

I have used your suggestion but not able to get them into an object array. I get them in the console but not in real like in ajax and in php
Because brokenImages.current_url = currentUrl; brokenImages.broken_src = brokenSrc; run before .on('error')
@user3278839 That would be a bit tricky. You need to create your object array int the $(function(){ scope. Then your error handler will store broken image links into the array, and use that array after it's populated.
@lkp111138 can you please edit your answer solve my problem like as you saying
Or you may want to $.post every time your handler is ran because there doesn't seem to be an "on everything has finished loading" event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.