user5497904
user5497904

Reputation: 1

If image src on JSON response is empty how to set default local image

in my chrome extension i want to view image and text in popup window

everything is working but if json data for image src is empty i am unable to set default image. I have tried mane alternate solutions from stack overflow but dint help. So please don't duplicate it or refer it with another solutions.

this is my popup.html

   <img id="img" />

this is my popup.js

var image = document.getElementById('img');

var jsonData = JSON.parse(myData);
image.src = jsonData["details"].imageUrl;

I am using ajax post request to get data from server side. this code i added on success part.

Problem: wehn image src is empty i need to set a default value inside my ajax call. what i have tried one of 15 different tries:

fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=orgLogox.length;
for(i=0;i<orgLogox.length;i++){
    var t = orgLogox[i];
    if(t.naturalWidth === 0){
       //this image is broken
         t.src = url;
     }
   }
}

Upvotes: 0

Views: 1157

Answers (2)

user5497904
user5497904

Reputation: 1

Solution: I solved it this way

image.onerror = function () {
this.src = 'default.png';
};
image.src = jsonData["details"].imageUrl;

Got help from this link :

Test to see if an image with json value is broken/ or not there and replace with "no-photo" image?

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can check your image url before setting it to img tag.

var jsonData = JSON.parse(myData);
var url = jsonData["details"].imageUrl;
if(!url || url == ""){
    image.src = "default.png"
}else{
    image.src = url;
}

Upvotes: 1

Related Questions