I want to show below json data on html table.how can i show to html table when i try to show with below code its show mae undefined
[
{
"Key": "data",
"Value": [
[
{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [
{
"Key": "cursors",
"Value": [
{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}
]
}
]
Below is my Code and its show me undefined
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd'>" + item.ID + "</td>"
+ "<td class='prtoducttd'>" + item.Message + "</td>"
+ "</tr>";
$('#tblPost tbody').append(rows);
});
}
what is generic method to parse the json and show it to html table?
Out put
id message created_time
116312453556631_122404992947377 "My message" "2020-09-27T21:38:10+0000"
Check if item.Key == "data". If it is, loop through item.Value to get the values for that row.
var data = [{
"Key": "data",
"Value": [{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [{
"Key": "cursors",
"Value": [{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}]
}
];
$.each(data, function(i, item) {
if (item.Key == "data") {
let id, message, created;
$.each(item.Value, function(j, obj) {
switch (obj.Key) {
case 'id':
id = obj.Value;
break;
case 'message':
message = obj.Value;
break;
case 'created_time':
created = obj.Value;
break;
}
});
debugger;
let rows = "<tr>" +
"<td class='prtoducttd'>" + id + "</td>" +
"<td class='prtoducttd'>" + message + "</td>" +
"<td class='prtoducttd'>" + created + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblPost">
<thead>
<tr>
<th>ID</th>
<th>Message</th>
<th>Created Time</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Make sure you're getting the data correctly first
For example, at item[0] see if the scope chain shows object available. Use the debugger and console to look through the data structure to follow the scope chain. Then write a loop once you've got the item and i correctly.
$.each(data, function (i, item) {
for (i = 0; i < item.Value.length; i++) {
let rows = "<tr>" +
"<td class='prtoducttd'>" + item.Value[i][2].Value + "</td>" +
"<td class='prtoducttd'>" + item.Value[i][1].Value + "</td>" +
"<td class='prtoducttd'>" + formatDate(new Date(item.Value[i][0].Value)) + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});
Related
I have a form which is currently doing a simple calculation. I have a button to duplicate the same form with an increment id and I need to do the calculations of the forms added independently.
var myJson = {
"platforms": [{
"name": "Sitecore",
"id": "Sitecore",
"tasktype": [{
"name": "Promobox",
"id": "Promobox",
"components": [{
"name": "Box 0",
"id": "box0",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "Video",
"components": [{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "Siab",
"tasktype": [{
"name": "Newswire",
"id": "Newswire",
"components": [{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "Task Type New",
"components": [{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function(index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function() {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function(index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function() {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function(index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function() {
$('#calculate').click(function() {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc input, #calc select').each(function(index) {
var input = $(this);
$(tr).append('<td class=row-' + $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor * units;
$(tr).append('<td>' + total + '</td>');
});
});
$(document).ready(function() {
var calc_index = 0;
$("#addNew").click(function() {
calc_index++;
$("#calc").after($("#calc").clone().attr("id", "calc" + calc_index));
$("#calc" + calc_index).css("display", "inline");
$("#calc" + calc_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + calc_index);
$(this).attr("id", $(this).attr("id") + calc_index);
});
});
});
$(document).ready(function() {
$('#calculate').click(function() {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc1 input, #calc1 select').each(function(index) {
var input = $(this);
$(tr).append('<td class=row-' + $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor * units;
$(tr).append('<td>' + total + '</td>');
});
});
$("#clear").click(function() {
location.reload();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Production Units Calculator</h2>
<div class="formset">
<form id="calc">
<label>Platform:</label>
<select id="platform" name="platform">
<option value="0">Select Platform</option>
</select>
<label>Task Type:</label>
<select id="tasktype" name="tasktype">
<option value="0">Select Task Type</option>
</select>
<label>Component:</label>
<select id="component" name="component">
<option value="0">Select Component</option>
</select>
<label>Units:</label>
<input name="units" id="units" type="number" min="0" placeholder="Input Units" />
<br />
</form>
</div>
<button id="calculate">Calculate</button>
<button id="addNew">Add New</button>
<button id="clear">Clear</button>
<table style="width:50%" id="data">
<thead>
<tr>
<th>Platform</th>
<th>Task Type</th>
<th>Component</th>
<th>Units</th>
<th>Time</th>
</tr>
</thead>
<tbody></tbody>
</table>
I was able to duplicate form with an increment ID however once the form is duplicated by clicking on add new , duplicated form doesn't work as the first one.
Please check this fiddle
You need to consider the change event for duplicate ID too.
$("#addNew").click(function() {
calc_index++;
$("#calc").after($("#calc").clone().attr("id", "calc" + calc_index));
$("#calc" + calc_index).css("display", "inline");
$("#calc" + calc_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + calc_index);
$(this).attr("id", $(this).attr("id") + calc_index);
});
//TODO
$.each(myJson.platforms, function(index, value) {
var platform_id;
var tasktype_id;
var component_id;
pID = "#platform" + calc_index;
tID = "#tasktype" + calc_index;
cID = "#component" + calc_index;
$(pID).append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$(pID).change(function() {
$(tID, cID).find("option:gt(0)").remove();
$(tID).find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function(index1, value1) {
$(tID).find("option:first").text("Select Task Type");
$(tID).append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$(tID).change(function() {
$(cID).find("option:gt(0)").remove();
$(cID).find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function(index2, value2) {
$(cID).find("option:first").text("Select Component");
$(cID).append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
I am using a jquery method to load JSON objects from the database. Then, I would want to display the record row by row in a HTML table. As can be seen in my JS file, I have tried to use a for and for each loop to loop through the data records but none of them are working apparently. My table seems to not display anything on the table or even error on result/ console log. However, there are data in my network log.
The json record in the network log is:
data: [
0:{
"id": "1",
"name": "John",
"type": "Client"
},
1:{
"id": "2",
"name": "Damen",
"type": "Agent"
},
2:{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
The HTML page is:
<table id="report" class="table table-bordered table-striped table-hover js-basic-example dataTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
app.viewReport();
</script>
My JS page is:
viewReport : function() {
$.ajax({
url: "/FIS/back-api/client/transaction/view",
dataType: "json",
method : 'GET',
success : function(data){
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].id+ "</td>");
tr.append("<td>" + data[i].name+ "</td>");
tr.append("<td>" + data[i].type+ "</td>");
$('#report tbody').append(tr);
}
}
/*$.each(data,function(i,item){
$('#report tr.odd').remove();
$("#report tbody").append(
"<tr>"
+"<td>"+item.id+"</td>"
+"<td>"+item.name+"</td>"
+"<td>"+item.type+"</td>"
+"</tr>" )
})
}*/
})
},
John , your JSON is invalid , this is the closest valid JSON i prepared from sample you shared above :
[
{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
Notice that for an array of objects 0 : {} format is invalid, so when you query it in a loop you're not receiving any result.
Incorrect :
0:{
"id": "1",
"name": "John",
"type": "Client"
}
Correct :
{
"id": "1",
"name": "John",
"type": "Client"
}
How to validate your JSON
Following sites will help you verify your json :
jsonlint
jsoneditoronline
Answer
Re-generate your JSON and then proceed as indicated in other answers.
Also , i would advice against parsing the result as string ! In my humble opinion, the proper way to do this is to return a valid json from Backend/server
Your data array is having keys, which is incorrect json format, If its an array it should look like:
[
{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
Process your JSON data correctly like Winnie said in another answer of this question. Then you have not defined table row correctly.
for (i = 0; i < data.length; i++) {
$('#report tbody').append(
$('<tr>').append(
$('<td>').text(data[i].id),
$('<td>').text(data[i].name),
$('<td>').text(data[i].type)
)
);
}
try to append it like this
for (var i = 0; i < data.length; i++) {
var htm = '';
htm += '<tr>';
htm += "<td>" + data[i].id.toString() + "</td>";
htm += "<td>" + data[i].name.toString() + "</td>";
htm += "<td>" + data[i].type.toString() + "</td>";
htm += '</tr>';
$('#report tbody').append(htm);
}
var data = [{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
];
for (var i = 0; i < data.length; i++) {
var body = document.getElementById("tableBody");
var row = body.insertRow();
for (var item in data[i]) {
var cell = row.insertCell();
cell.innerHTML = data[i][item];
}
}
<html>
<body>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</body>
</html>
I have a JSON file that contains an array of 3 objects.
When I want to display an object's attribute it display the name of it, for instance if I have an object car that has an attribute called name and has the value "FIAT" when I write car.name it displays " CAR.NAME " on the the listview instead of FIAT.
Here's my code.
$.getJSON("res/jsonFile/produits.json", function(products) {
$('#productList').empty();
$.each(products, function(i, product) {
$('#productList').append(productLink(product));
});
$('#productList').listview('refresh');
});
function productLink(product) {
var link="<li>" +
"<img src=product.pic>" +
"" +
"<h2>product.name</h2>" +
"<p>product.desc</p>" +
"<p>product.price</p>" +
"</li>";
return link;
}
and here's my JSON file
[
{
"name": "Coca Cola",
"desc": "Coca Cola",
"price": 10,
"qty": 100,
"pic": "img/coca cola.jpg"
},
{
"name": "Fanta",
"desc": "Fanta mini",
"price": 10,
"qty": 100,
"pic": "img/fanta.jpg"
},
{
"name": "Salade niçoise",
"desc": "Salade",
"price": 15,
"qty": 100,
"pic": "img/nicoise.jpg"
}
]
In your function you're printing the variable names, not their values. Use it like this instead:
function productLink(product) {
var link="<li>" +
"<img src=" + product.pic + ">" +
"<h2>" + product.name + "</h2>" +
"<p>" + product.desc + "</p>" +
"<p>" + product.price + "</p>" +
"</li>";
return link;
}
I am working with an API that is returning data in JSON format. An example of a response is this
{
"code": 200,
"count": 4,
"currentPage": 1,
"date": "2013-05-24T09:19:37.964+1000",
"executedQuery": "cafe",
"message": "OK",
"originalQuery": "cafe",
"results": [{
"aboutId": "b3ec5ac4096078f89fa4a9f3adcec930a1d4997c7cae30b026d61f8fcbf2013b",
"categories": [{
"id": "35491",
"name": "Cafes",
"sensitive": false
}],
"detailsLink": "http://www.yellowpages.com.au/nsw/mt-colah/bobbin-inn-13830124-listing.html?referredBy=TAPI-jHOsyHrSfHBBlo0IExDjXZZJx6PszwX6",
"hasExposureProducts": false,
"id": "13830124",
"listingType": "Business",
"name": "Bobbin Inn",
"primaryAddress": {
"addressLine": "1 Chase Rd",
"geoCodeGranularity": "PROPERTY",
"latitude": "-33.678276",
"longitude": "151.112964",
"mappable": true,
"postcode": "2079",
"state": "NSW",
"suburb": "Mt Colah",
"type": "PHYSICAL"
},
"primaryContacts": [{
"type": "PHONE",
"value": "(02) 9457 7170"
}],
"pureMobileBusiness": false,
…
From what i can tell there is a number of arrays in this response. I am failing however to parse this data on a create method
here is my code (this is working for this field i have defined but ... see below)
for (var i in p) {
str += blocka + uibare + p.executedQuery + " (" + p.executedQuery+ ")</div></div>";
str += blockb + uibarc + p.executedQuery + "</div></div>";
str += blockc + uibare + p.executedQuery + "</div></div>";
str += blockd + uibarc + p.executedQuery + "</div></div>";
str += blocke + uibare + p.executedQuery + "</div></div>";
}
This is working, because executedQuery is not part of the array. However if i want to get for example the "name" that appears to be part of the results array? Or am i reading it wrong?
so i tried
str += blockb + uibarc + p.results[i].name + "</div></div>";
and it won't pull any data.
results is an array that contains a single object of keys and values.
Try result[0]["name"].
More suitable to your request:
str += blockb + uibarc + p.results[0]["name"] + "</div></div>";
I need to fetch the values from this JSON in my java script this is coming from jsp:
[{
"selectionName": "Select",
"subSelections": [{
"id": 4,
"subSelectionName": "Select",
"description": "Deepmala"
}
]
}, {
"selectionName": "week14",
"subSelections": [{
"id": 7,
"subSelectionName": "1",
"description": ""
}
]
}, {
"selectionName": "test",
"subSelections": [{
"id": 6,
"subSelectionName": "test",
"description": ""
}
]
}, {
"selectionName": "select",
"subSelections": [{
"id": 3,
"subSelectionName": "sub-select",
"description": "Created by Prakash"
}
]
}, {
"selectionName": "testcreate",
"subSelections": [{
"id": 1,
"subSelectionName": "testcreate",
"description": ""
}
]
}, {
"selectionName": "by htmlwidget",
"subSelections": [{
"id": 5,
"subSelectionName": "by htmlwidget",
"description": "created by html widget"
}
]
}
]
Any suggestions? I am tring to fetch it like this:
function getSelection() {
var options = "";
$.getJSON('../r3/selection.jsp').done(function(json) {
//alert(json.selectionName);
// alert(json.subSelections);
// options += '<option value="' + value. selectionId + '">' + value.selectionName + '</option>';
$.each(json.subSelections, function(index, value) {
options += '<option value="' + value. subSelectionName + '">' + value. description + '</option>';
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$(document.body).append(select);
}).fail(function (jqxhr, textStatus, error) {
alert(' fail json : '+error);
});
}
//alert(json.selectionName);
// alert(json.subSelections); inside the loop gives me undefined value.
Try this:
$.each(json, function (key, data) {
$.each(data.subSelections, function (index, values) {
options += '<option value="' + values.subSelectionName + '">' + values.description + '</option>';
});
});
var select = $('<select id="selection" onchange="getSubselection()"/>');
select.append(options);
$('body').append(select);