skip to Main Content

I am trying to build a basic covid19 website. the code I am using is only returning [object Object] in the actual data. What I am doing wrong here?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.getJSON("https://api.covid19api.com/summary", function(result){
      $.each(result, function(i, field){
        $("div").append(field + " ");
      });
    });
  });
});
</script>
</head>
<body>

<button>Get JSON data</button>

<div></div>

</body>
</html>

3

Answers


  1. <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $.getJSON("https://api.covid19api.com/summary", function(result){
          $.each(result.Countries, function(i, field){
            $("div").append("<span>"+JSON.stringify(field)+"</span></br>");
          });
        });
      });
    });
    </script>
    </head>
    <body>
    
    <button>Get JSON data</button>
    
    <div></div>
    
    </body>
    </html>
    Login or Signup to reply.
  2. That’s because you’re trying to append JavaScript object to DOM. Instead, see what data you’re getting (as someone mentioned in comments, by console.log) then you can edit your append part accordingly.

    Login or Signup to reply.
  3. Here I have a sample answer which appends all list of country. Understand each and every line and function how it works. I have appended list of country, how to render the rest items that I leave it to you. Don’t get discouraged or disappointed; learning to code is a journey, not destination.

    Note:https://cors-anywhere.herokuapp.com/ is added if you are running it in your localhost to avoid CORS’s problem. If you have hosted the page, you can remove it.

        $(document).ready(function(){
        $("button").on('click',function(){
        $.getJSON("https://cors-anywhere.herokuapp.com/https://api.covid19api.com/summary", function(result){
                   var obj=result;
                   var json = JSON.stringify(obj);
                   var s = JSON.parse(json);
                   s.Countries.map(function(c){
                         $("#result").append("<span>"+c.Country+"</span></br>");
                   })
                   console.log(s.Countries[0].Country);
        });
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search