Search code examples
javascriptjqueryjsonapireturn

I Cant return image I want when value is null


Im trying to return a default image if the image i'm pulling from my api is null, but anything I put wont return my default/placeholder image, I tried null, void, false, etc, nothing works, and when I put value = "", it displays my default image even when its not null,

what json looks like json from api

Area im trying to get working from app3.js//////////////////////////////////////////////////////////////////////////////////

 var $img2 = $("<img />").attr('src', data2.events["1"].performers["0"].image );

    var userImage = $("<img />").attr("src","https://imagemagick.org/image/gradients/linear_gradient.png");

         var $imgnew = ($img2, (key, value) => {
  if (value ===  null) {
    return userImage;

  }
  return value;
}
)  

$('#img2').append($imgnew);

Full json /////////////////////

{meta: {…}, in_hand: {…}, events: Array(10)}
meta: {geolocation: null, per_page: 10, total: 14, took: 4, page: 1}
in_hand: {}
events: Array(10)
0: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5055747, …}
1:
links: []
event_promotion: null
conditional: false
is_open: false
id: 5161557
stats: {visible_listing_count: null, dq_bucket_counts: null, average_price: null, lowest_sg_base_price_good_deals: null, lowest_price_good_deals: null, …}
title: "Amarillo Venom at Salina Liberty"
announce_date: "2019-12-21T00:00:00"
score: 0.361
access_method: null
announcements: {}
taxonomies: (2) [{…}, {…}]
type: "football"
status: "normal"
description: ""
datetime_local: "2020-03-21T13:00:00"
visible_until_utc: "2020-03-21T22:00:00"
time_tbd: false
date_tbd: false
performers: Array(2)
0: {image: null, primary: true, colors: null, images: {…}, has_upcoming_events: true, …}
1: {image: null, colors: null, images: {…}, has_upcoming_events: true, id: 114910, …}
length: 2
__proto__: Array(0)
url: "https://seatgeek.com/amarillo-venom-at-salina-liberty-tickets/football/2020-03-21-1-pm/5161557"
created_at: "2019-12-21T16:00:49"
popularity: 0.46
venue: {links: Array(0), metro_code: 678, postal_code: "67401", timezone: "America/Chicago", has_upcoming_events: true, …}
enddatetime_utc: null
short_title: "Amarillo Venom at Salina Liberty"
datetime_utc: "2020-03-21T18:00:00"
datetime_tbd: false
__proto__: Object
2: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5161560, …}
3: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251570, …}
4: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251569, …}
5: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251400, …}
6: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251566, …}
7: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251567, …}
8: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251568, …}
9: {links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251565, …}
length: 10
__proto__: Array(0)
__proto__: Object

Full app3.js ////////////////////////////////////////////////////////////////////////

function myFunction() {
  var x = document.getElementById("myText").value;
  document.getElementById("demo4");



            var list = 'boston';
            var list2 = 'celtics';

                            $.getJSON("https://api.seatgeek.com/2/events?q="+x+"&client_id=MjA1NTgxMTN8MTU4MDY3MjIzNy43OQ", function(data2) {


        //        events["0"].performers["0"].image


                  var $img = $("<img />").attr('src', data2.events["0"].performers["0"].image);

                  var $img2 = $("<img />").attr('src', data2.events["1"].performers["0"].image );

       //         var $img = $("<img />").attr('src', data2.events.performers[0].images.huge); 

                           //     events[1].performers[""0""].image

                var list3 = data2.events;

                var event2 = list3.title;                



                var list5 = data2.events["0"].title;    

                 var price1 = data2.events["0"].stats.average_price;                


//                var list5new = list5 + " " + price1;                


                var list6 = data2.events["1"].title;                 

                var price2 = data2.events["1"].stats.average_price;                  

//                var list6new = list6 + " " + price2;



                var list7 = data2.events["2"].title;

                 var price3 = data2.events["0"].title;                 




                 var buy = data2.events["0"].url;


                 var buy3 = data2.events["1"].url;    

       //         console.log(href);


//                 var str = "Free Web Building Tutorials!";
   var buy2 = buy.link(data2.events["0"].url);                

   var buy4 = buy3.link(data2.events["0"].url);                              




                var hi = 'NA'     

    var newlink = (JSON.stringify(list5, (key, value) => {
  if (value === undefined) {
    return hi;

  }
  return value;
} 
))     


//    if (list5.value === "undefined"){
//    console.log('the property is not available...'); // print into console
//}


//                                
//  if (typeof list5 === "undefined") {
//    txt = "x is undefined";
//      
//    console.log('nada')  
//  } else {
//    txt = "x is defined";
//  }                                
//                                
          // var userImage = "https://imagemagick.org/image/gradients/linear_gradient.png"; 

                         //      var userImage2 = "https://imagemagick.org/image/gradients/linear_gradient.png"; //
    var userImage = $("<img />").attr("src","https://imagemagick.org/image/gradients/linear_gradient.png");

         var $imgnew = ($img2, (key, value) => {
  if (value.getAttribute('src') == "") {
    return userImage;

  }
  return value;
} 
)                    


                var hi = 'NA'

    var link1 = (JSON.stringify(price1, (key, value) => {
  if (value === null) {
    return hi;

  }
  return value;
} 
))

                    var hi = 'NA'

    var link2 = (JSON.stringify(price2, (key, value) => {
  if (value === null) {
    return hi;
  }
  return value;
} 
))
      //          console.log(list3)

          //      console.log(list5new)  
                console.log(data2)  


                 $("#demo4").append(list5 + " - " + "Price" + " " + link1 );
                 $("#link").append( buy2);                
                 $("#demo5").append(list6 + " - " + "Price" + " " + link2);                
                 $("#link2").append(buy4);
                 $('#img1').append($img);
                 $('#img2').append($img2);    
             //        $('#img3').append(userImage);                                  

                 $(document).ready(function(){

//                                                 $("p").click(function(){
//    alert("The paragraph was clicked.");    
//
//                                                 });
            if( $("#demo4").css('display') == 'none')  {
            $("#error").show();
        }

                });

                $(document).ready(function(){

            if( $("#demo4").css('display')) {
            $("#error").hide();
        }


            $("button").click(function(){
            $("#error").hide();
  });
                });

});
//            $.getJSON("https://api.seatgeek.com/2/events?q=boston+celtics&client_id=MjA1NTgxMTN8MTU4MDY3MjIzNy43OQ", function(data2) {
//    //data is the JSON string 
//                console.log(data2);
//});

}

Html //////////////////////////////////////////////////////

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Event finder</title>
  <link rel="stylesheet" href="style2.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>     

</head>
<body>






 <div id="top"> 
    <h2>FindYourTickets</h2>

    <br>

    <h2 class="hi">Get Started here</h2>
    <br>
    </div>
   <br>
    <div class="center">

<!--        <h2>City</h2>-->
            <input id="myInput2" type="text" placeholder="City(Optional)">

    <br>    
<!--        <h2>Search</h2>-->

    <br>




  <input type="text" id="myText" placeholder="Search" value="">

<p></p>

<button class="button" onclick="myFunction()"><h2>Search</h2></button>    




    <br>
    <br>

    <button class="button"><a href="index3.html"><h2>Clear</h2></a></button>






    </div>
<br><br>
<!--
<div id="myDIV">
  <p>I am a paragraph.</p>
  <div>I am a div element inside div.</div>
  <button>I am a button</button>
  <button>Another button</button>
  <p>Another paragraph.</p>
</div>
-->


    <!-- <div class="main">
    <div class="header">
      <h1>OpenWeatherMap API</h1>
      <p>Enter any city name in the input box below to get the data</p>
    </div> -->

<!--
   <button type="button" onclick="alert('Hello world!')">Click Me!</button>
<h1 class="name2" id="name2">hi</h1>  
-->

<script src="app3.js"></script>

<!--
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>  
-->

<!--     <div id="img3"></div>-->
    <div id="wrapper">
    <div id="error"> <h4>No results</h4></div>
 <div id="demo4"></div>   
   <div id="link"></div>

        <div id="img1"></div>

        <br>
        <br>
           <br>
        <br>

        <div id="demo5"></div>  
  <div id="link2"></div>

        <div id="img2"></div>



    <span class = "my_class"></span>




          <ul id="result2"> </ul> 



    </div>



</body>
</html>

Solution

  • Your code is more complicated than it needs to be. You simply need to determine if the image property is empty/null and then provide a default if it is. As such you can use the || to coalesce the empty value to your default path. Try this:

    var imgSrc = data2.events[1].performers[0].image || "https://imagemagick.org/image/gradients/linear_gradient.png";
    $("<img />").prop('src', imgSrc).appendTo('#container');

    Note that the new img element is being appended to another element. Your original was trying to append an img within an img which is not possible.