Reputation: 7138
I'm having issue with appending my data to table body.
$.ajax({
type:'GET',
url:'{{url('dashboard/customer-groups')}}/'+ordID,
success:function(data){
console.log(data); //screenshot below
}
});
data returned by ajax code above in 2 categories (group and customers)
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th> // from customers array
<th>Company</th> // from customers array
<th>Province</th> // from customers array
<th>City</th> // from customers array
<th>Email</th> // from customers array
<th>Industry</th> // from customers array
<th>Group</th> // from group
</tr>
</thead>
<tbody id="table_customer"></tbody>
</table>
Any idea?
Upvotes: 1
Views: 334
Reputation: 1393
$.ajax({
type:'GET',
url:'{{url('dashboard/customer-groups')}}/'+ordID,
success:function(data){
const tr = $('tr');
for (var key in data) {
var obj = data[key];
var id = "<td>"+obj.id+"</td>";
var group_id = "<td>"+obj.group_id+"</td>";
// add more columns for other attributes
var allTds = id+group_id;
}
tr.append(allTds);
$('#data-table').append(tr);
}
});
Upvotes: 0
Reputation: 68933
You can loop through the response data and append them in the table body using .each()
on success.
Demo:
let data = {customers: [
{id: 1, name:'John', group_id: 111, industry_id: 'xyz', company: 'abc', province: 'aaa', city: 'vv', email: '[email protected]'},
{id: 2, name:'Kate', group_id: 222, industry_id: 'lmn', company: 'abc2', province: 'bbb', city: 'qq', email: '[email protected]'}
]};
$(data.customers).each(function(_, i){
var row = `<tr><td></td><td>${i.name}</td><td>${i.company}</td><td>${i.province}</td><td>${i.city}</td><td>${i.email}</td><td>${i.industry_id}</td><td>${i.group_id}</td></tr>`;
$('#table_customer').append(row);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data-table" class="table table-striped table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Company</th>
<th>Province</th>
<th>City</th>
<th>Email</th>
<th>Industry</th>
<th>Group</th>
</tr>
</thead>
<tbody id="table_customer"></tbody>
</table>
Upvotes: 2