0

I am trying to get data from API and display them using AJAX I have this code

 $(document).ready(function(){  
          $('.show').click(function(){     
          $.ajax({
           url: 'url',
           dataType: 'json',
           success: function(data) {
              var items = [];
              $.each(data, function(key, val) {

                items.push('<li id="' + key + '">' + val + '</li>');    

              });

              $('<ul/>', {
                 'class': 'interest-list',
                 html: items.join('')
              }).appendTo('body');

           },
          statusCode: {
             404: function() {
               alert('There was a problem with the server.  Try again soon!');
             }
           }
    });
    });
    });

I have this result:

[object Object],[object Object],[object Object],[object Object],

What must I fix in my code?

2
  • @Islam Elshobokshy ,it must be added to the body,but it just add [Object Object],[object Object],[object Object],[object Object]. Commented Feb 18, 2019 at 14:10
  • code - jsfiddle.net/8ut5q62k Commented Feb 18, 2019 at 14:21

2 Answers 2

1

$.each iterates over the array, and key was the index of the array, and val was the entire object

You could change this line of code

items.push('<li id="' + key + '">' + val + '</li>');

to

var key = Object.keys(val)[0];
items.push('<li id="' + key + '">' + val[key] + "</li>"); 

to just get the first key directly. Here is the documentation for Object.keys.

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you'd better add the type:'GET' field to define what kind of call are you doing. Then you can use var json = JSON.parse(data) to read all the incoming data from data like this:

var time = json['foo'];

or if you have an array:

var time = json[index]['foo'];

you can find more details here https://www.w3schools.com/js/js_json_parse.asp and here https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

1 Comment

The default type is GET, dataType is set to json so the data is already converted and you don't use JSON.parse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.