-1

Since few days i am stuggling with some problem on img replace in javascript. I am coding this application with course, but in this course video img replacing work well. probably main cause is that I fetch other API. Its opportunity for me to learn how to solve this kind of problems but i can't find answer since few days.

Here is my code: https://codepen.io/sowicz/pen/xxjyXVO

And problem is in this lines below. Because of some serials data from json can't be load (GET 404 error) I want to replace img for some img from pixabay. Unfortunately it doesn't work. I can't solve this issue.

if(serials.Poster) {
                imgSrc = serials.Poster;
            } else {
                this.imgSrc = "https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg"
            }   

I am very sorry if something is missing, I am new in coding. Thanks a lot in advance, and wish you good day!

sowicz
  • 3
  • 2

2 Answers2

2

this.imgSrc = is same as showsApp.imgSrc. the problem is you use imgSrc as local var to call method getShowBoxByTemplate.

I think we should change it into

let imgSrc = null;

if (serials.Poster) {
    imgSrc = serials.Poster;
} else {
    imgSrc = "https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg"
}   

or

const imgSrc = !!serials.Poster ? serials.Poster : "https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg"

or

const imgSrc = serials.Poster || "https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg"

if your image responds with 404 code you can use onerror event like the example here

<img src="${imgSrc}" onerror="this.src='https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg'" alt="">
nhy
  • 169
  • 1
  • 2
  • 7
  • Many thanks for answer! The same results, img from pixabay don't load. Console shows: GET 404 error – sowicz Oct 08 '22 at 10:56
  • i did edit answer with the part to handle image response with code 404. you can use ` ` for the `` in method `getShowBoxByTemplate` – nhy Oct 08 '22 at 11:05
  • Thank a lot! now it works! I still got errors in console 'GET 'link' 404' error - so i need to try solutrion from Sascha Scherrer. Thank you guys! – sowicz Oct 08 '22 at 11:10
  • This should be the correct solution. The API returns a value for `serials.Poster` meaning the `if` statement always sets `imgSrc` to `serials.Poster`. The 404 message means the image URL the API returned is not found on the server, which is the API/server's fault. Using `onerror` is how you should handle missing/invalid image URLs. – EssXTee Oct 08 '22 at 11:26
-1

You attempt to use the fallback image, if your API's data does not provide an image URL. Please note that as an image URL is provided (albeit it points to a location that does not exists) your else-Block ist not executed in this case. This is because

if ( serials.Poster )

just checks, that the attribute Poster is present in the object "serials". It completely ignores whether this contains a valid URL or even points to an existing location.

If you want to check in vanilla JS whether that image can be loaded from it's URL, I suggest you do an XHR and check the status for the 20X-range. See HTTP Status Code from URL in Javascript for more detail.

I suggest you try that in isolation, so you can better narrow the issue down. You can use

let serials = {
    "Poster": "https://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_UX182_CR0,0,182,268_AL_.jpg"
}

if ( serials.Poster ) { // TODO: improve this
    imgSrc = serials.Poster;
} else {
    imgSrc = "https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg";
}  

console.log("imgSrc:", imgSrc);

and try out what happens if you misspelled Poster to understand what I mean.

EDIT / APPENDING:

As nyx's answer already pointed out the probably simplest way to achieve this is by adding an onerror-Handler to the affected image tag.

getShowBoxByTemplate: function(imgSrc, title, date, overview){
return `
    <div class="show-box">
        <img src="${imgSrc}" alt="Movie Poster for ${title}" onerror="this.src='https://cdn.pixabay.com/photo/2022/03/31/11/28/snakes-head-fritillary-7102810__340.jpg'">
        <div class="show-tittle">${title}</div>
        <div class="Date">${date}</div>
        <div class="show-overview">${overview}</div>
    </div> 
`
} 
Sascha S.
  • 24
  • 5
  • Thank you sir so much! I have tired 3 days but can't find solution. Already checked the status of URL and confirm but I can't use if statement to provide url from server or from other source. The if statement always has done before XHR have results. I have to stop then i learn a bit more about async. – sowicz Oct 12 '22 at 15:49
  • I think the solution originally proposed by nhy's answer is way more elegant than my initial suggestion to check the resource via XHR. So I suggest you make your life easier by adopting the onerror-Handler to set the intended fallback image. Please consider marking nhx's answer as the accepted answer, so others will find the elegant and working solution quicker. – Sascha S. Oct 13 '22 at 23:48