0

JSON (inside array from api):

[{"id":"001", "name":"john", "age":"40"}, {"id":"002", "name":"jane", "age":"30"}]

Ajax:

  $.ajax({                                      
  url: 'interface_API.php',                                                              
  dataType: 'json',                    
  success: function(data)         
  {
    for(var i in data){
        var row = data[i];

        var id = row[0];            
        var name = row[1];
        var age = row[2];

    $('#output').append("<tr width='50%'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>"); 
    }
  } 
});

The API uses this to construct:

if(mysqli_num_rows($output)){
     while($row = mysqli_fetch_assoc($output)){
         $json[] = $row;
     }
}

However my Output is 'undefined' repeated for each .append

How do i extract each json object from the array & append to the page?

3
  • 2
    Have you tried using console.log to see what data actually contains? Commented Jul 21, 2014 at 9:14
  • 2
    You should be using a regular for loop for an array, and to access the objects properties you'd do row.id etc. not row[0]. Commented Jul 21, 2014 at 9:15
  • do you get proper reponse/output of interface_API.php? Commented Jul 21, 2014 at 9:17

3 Answers 3

1

change this:

var id = row[0];            
var name = row[1];
var age = row[2];

to this:

var id = row['id'];            
var name = row['name'];
var age = row['age'];

or this:

var id = row.id;
var name = row.name;
var age = row.age;

Because you already looped in here:

for(var i in data){
    var row = data[i]; // <----here

so you just required to reference it with keys in the js object.

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

1 Comment

i will accept this answer after the timeout as you were first to answer. thank you
0

You can change the for loop like this:

$.ajax({                                      
  url: 'interface_API.php',                                                              
  dataType: 'json',                    
  success: function(data)         
  {
    for(var i in data){
        var row = data[i];

        var id = row.id;            
        var name = row.name;
        var age = row.age;

$('#output').append("<tr width='50%'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>"); 
}
} 
});

Comments

0

please use the key to identify the json Object while retrieving

var list=[
        {"id":"1","text":"test1"},
        {"id":"2","text":"test2"},
        {"id":"3","text":"test3"},
        {"id":"4","text":"test4"}

         ]


    alert(list[2].id)

Comments

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.