ThomH ThomH - 6 months ago 16
Javascript Question

Can't append variable but can console log it

I've struggled with this problem for a while but I can't seem to figure it out. I'm trying to loop through the JSON object and append the data for each array to a div in my index.php. But it's not working somehow I can however

console.log
the data but not append it.

var result;
getData();

function getData() {
$.ajax({
type: "POST",
url: 'api/api.php',
data: {
'information' : 'info'
},
async: false,
success: function(data) {
result = data;
},
dataType: 'HTML'
});

result = $.parseJSON(result);
//console.log(result[1].naam);
}

function dumpData(){
console.log(test);
for(var i = 0; i <= result.length; i++) {
console.log(result[i].naam);
$('<tr>').append(
$('<td>').text(result[i].id),
$('<td>').text(result[i].naam),
$('<td>').text(result[i].brouwer)
).appendTo('#test');
}
}

console.log('Loaded data.');
dumpData();
console.log('Dumped data.');


Index.php:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="js/Database.js"></script>

<body>
<div id="test"></div>
</body>


UPDATE:
dataType was meant to be JSON instead of HTML this was the problem.

Answer

The canonical way to do what you are trying is to not use async:false, to append in the success of the call and to append the rows to a table.

You also loop once too many with the <=

Also your code relies on the result to be correct JSON and not HTML as in

var result = [ 
  { "id":"0", "naam":"Thom", "brouwer":"Heineken" },
  { "id":"1", "naam":"Bram", "brouwer":"Amstel" },
  { "id":"2", "naam":"Aad", "brouwer":"Grolsch" } // no comma on the last
  ];


function dumpData(result){
    console.log(result);
    for(var i = 0; i < result.length; i++) {
        $('<tr>').append(
            $('<td>').text(result[i].id),
            $('<td>').text(result[i].naam),
            $('<td>').text(result[i].brouwer)
        ).appendTo('#test');
    }
}

console.log('Loaded data.');
dumpData(result);
console.log('Dumped data.');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tbody id="test"></tbody>
</table>

I would personally code the Ajax as

function getData() {
  $.ajax({
    type: "POST",
    url: 'api/api.php',
    data: {
        'information' : 'info'
    },
    success: function(data) {
        dumpData(data)
    },
    dataType: 'JSON'
  });
}

and have

function dumpData(data){
Comments