0

I will be getting a JSON response from a server

var  imagesdata = 
{
    "images": [
        {
            "image": "JSON_images/popcorn.jpg",
            "name": "Popcorn"
        },
        {
            "name": "Ice creams",
            "image": "JSON_images/icecream_cup.jpg"
        },
        {
            "name": "Snacks & Corn",
            "image": "JSON_images/puff_egg.jpg"
        },
        {
            "image": "JSON_images/thumsup_can.jpg",
            "name": "Soft Drinks"
        }
    ]
}





  for (var i = 0; i < imagesdata.images.length; i++) {
        var imagename = imagesdata.images[i].image;
        var name = imagesdata.images[i].name;
        callImage(imagename, name);
    }

    function callImage(imagename, name) {
        var divhtml = $('<div class="item">');
        divhtml.append('<i><img class = "imgclss" id="' + name + '" src="' + imagename + '" alt=""/></i>');
        divhtml.append('</div>');
    }

With the above JSON Data i am showing the images dynmaically on the User Interface as shown below and the User Interface looks this way

enter image description here

My question is that in case a particular image is not found under the JSON_images , how can i show a default image ??

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • Declare 'not found'? Would that be an empty `image` property in the JSON or a path to a nonexisting image? – Biketire Aug 25 '14 at 11:22
  • sorry , i ddin't get you , could you please elobrate ?? – Pawan Aug 25 '14 at 11:24
  • 1
    Maybe a mistake in the title? Do you mean `not found` ? In this case, have a look here: http://stackoverflow.com/questions/3984287/how-to-show-alternate-image-if-source-image-is-not-found-onerror-working-in-ie – Nicolas R Aug 25 '14 at 11:25
  • What I meant was: will you be getting this: `{"image": "", "name": "Soft Drinks"}` or this `{"image": "nonexistingimage.jpg", "name": "Soft Drinks"}` – Biketire Aug 25 '14 at 11:34

1 Answers1

1

I mean if your using jquery, you can do either one, find the one which has an error and replace it with an missing image or hide it.

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

or

// Or, hide them
$("img").error(function(){
        $(this).hide();
});

JSFIDDLE EXAMPLE: http://jsfiddle.net/zm3qndxo/

jagmitg
  • 4,236
  • 7
  • 25
  • 59
  • Thank you very much , but when i added this inside my code $('img').error(function(){ alert('missing imagee'); nothing got fired up . }); – Pawan Aug 25 '14 at 11:29
  • @PreethiJain edited my existing post with a jsfiddle – jagmitg Aug 25 '14 at 11:31