Reputation: 2694
I have an AJAX request which returns an array from my database like this:
$objet['name']
$objet['date']
$objet['amount']
When I do an each
function it does an iteration for each rows and keys,
I would like to make one iteration for each rows and to display data in table row. Below is my code :
$("#show_debours").dialog("open");
var groupe_debours = $(this).closest('tr').find('.groupe').val();
$.ajax({
type: "POST",
url: "requetes_ajax/fetch_debours_detail.json.php",
data: "groupe=" + groupe_debours,
success: function(data){
$('.remove').remove();
$.each(data, function (data) {
$('#fetchdebours tr:last').after('<tr class="remove"><td>' + data.libelle_debours + '</td><td>' + data.date + '</td><td>' + data.debours_montant_ht_tva + '</td><td>' + data.debours_montant_ht_no_tva + '</td><td>' + data.debours_montant_ttc + '</td></tr>')
//alert(key + ': ' + value);
});
}
});
});
All works fine, but instead of returning one row with all value, it returns as many rows as there is rows and variables
For example if I have 3 rows in my database it returns to me 9 lines in my table. It should not.
In php I do
<?php
foreach($data as $row):
echo "<tr><td>{$data['name']}</td><td>{$data['date']}</td>{$data['amount']}</tr>";
endforeach;
?>
This works fine it returns to me 3 row with all values filled. I would like the same in jQuery but I do not know how. I've done some research with no success.
Any kind of help will be much appreciated
Upvotes: 0
Views: 935
Reputation: 337560
It creates multiple rows because you are creating a tr
element in each iteration. Try this:
success: function(data){
$('.remove').remove();
var $tr = $('<tr />', { 'class': 'remove' });
$.each(data, function (data) {
$tr.append('<td>' + data.libelle_debours + '</td><td>' + data.date + '</td><td>' + data.debours_montant_ht_tva + '</td><td>' + data.debours_montant_ht_no_tva + '</td><td>' + data.debours_montant_ttc + '</td>');
});
$('#fetchdebours tr:last').after($tr);
}
Upvotes: 1