Reputation: 85
I'm trying to append the contactTable with new rows for each ContactID and ContactName from my json response in a table. I am receiving data into the console but when I try to insert that data into my html document, I get a undefined
value for each.
html result
<tr>
<th id="contactName"></th>
<th id="contactID"></th>
</tr>
<tr>
<td>undefined</td>
<td>undefined</td>
</tr>
index.html
<table id="contactTable">
<tr>
<th id="contactName"></th>
<th id="contactID"></th>
</tr>
</table>
script.js
$(document).ready(function () {
$.ajax({
url: 'https://api2.******.com/crm/v1/rest/taggroups/1/contacts',
type: 'GET',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
drawTable(JSON.stringify(data));
drawRow(JSON.stringify(data));
console.log(data);
// $('#contacts').html(JSON.stringify(data, null)); returns pretty json
{alert('Success! Enjoy your data!')};
},
error: function () { alert('Request failed'); },
beforeSend: setHeader
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#contactTable").append(row);
row.append($("<td>" + rowData.ContactName + "</td>"));
row.append($("<td>" + rowData.ContactID + "</td>"));
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ******');
xhr.setRequestHeader('content-type', 'application/json');
};
Here's the first record of the json response
Object
TagMembers:Array(185)
[0 … 99]
0:
ContactID:2732270
ContactName:"First Last"
RecAdd:"/Date(1427853954000-0700)/"
RecAddUser:0
RecID:3
TagGroupID:1
Upvotes: 1
Views: 137
Reputation: 85
Turns out I neede to make some changes to drawRow
function drawRow(data) {
var row = $("<tr />")
$("#contactTable").append(row);
row.append($("<td>" + data.ContactName + "</td>"));
row.append($("<td>" + data.ContactID + "</td>"));
}
Upvotes: 0
Reputation: 31
your data looks something like this:
var data = {
TagMembers: [
{ContactID:2732270,
ContactName:"First",
RecAdd:"/Date(1427853954000-0700)/",
RecAddUser:0,
RecID:3,
TagGroupID:4
},
{ContactID:2732275,
ContactName:"Second",
RecAdd:"/Date(1427853954000-0700)/",
RecAddUser:0,
RecID:4,
TagGroupID:5
},
{ContactID:2732277,
ContactName:"Third",
RecAdd:"/Date(1427853954000-0700)/",
RecAddUser:0,
RecID:5,
TagGroupID:5
}]
};
This means you should send to drowTable
function not data
and not JSON.stringify(data)
(no need to convert object to string), but array of data.TagMembers
: drawTable(data.TagMembers);
so you can loop objects and get data form each one of them.
And also no need to additional call to drawRow(JSON.stringify(data));
it is redundant, becase your already calling to it inside drowTable
function
Upvotes: 1