JSON Formatting Issue? - javascript

I am trying to populate an html table of JSON data. I was provided the JSON data and cannot determine why it isn't populating but suspect the JSON may not be formatted properly. When I use other sample data it works, then when I sub in the JSON I was provided it doesn't work. I've tried copying the JSON into a file on my direct server, linking to what I was provided (here: https://boiling-fortress-75456.herokuapp.com/) and inserting it on myjson.com and reformatting the JSON data.
Here is my code:
<script>
$(function() {
var entries = [];
var dmJSON = "https://api.myjson.com/bins/6sjud?callback=?";
$.getJSON(dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.rank + "</td>" + "<td>" + f.name + "</td>" + "<td>" + f.march_rank + "</td>" + "<td> " + f.april_rank + "</td>" + "<td>" + f.may_rank + "</td>" + f.personal_volume + "</td>" + f.team_volume + "</td>" + "</tr>"
$(tblRow).appendTo("#incentive tbody");
});
});
});
</script>
<div class="wrapper">
<div class="profile">
<table id= "incentive" border="1">
<thead>
<th>Rank</th>
<th>Name</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>Highest Rank</th>
<th>Personal Volume</th>
<th>Team Volume</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>

You need to get the objects from affiliate
$.each(data.affiliate, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.rank + "</td>" + "<td>" + f.name + "</td>" + "<td>" + f.march_rank + "</td>" + "<td> " + f.april_rank + "</td>" + "<td>" + f.may_rank + "</td>" + f.personal_volume + "</td>" + f.team_volume + "</td>" + "</tr>"
$(tblRow).appendTo("#incentive tbody");
});
Response from service
{
"affiliate":[{
"rank":1,"name":"Sally","march_rank":"Gold","april_rank":"Silver","may_rank":"Silver","highest_rank":"Silver","team_volume":12345
},{
"rank":2,"name":"Zelda","march_rank":"Gold","april_rank":"Bronze","may_rank":"Silver","highest_rank":"Gold","team_volume":12345
}
]
}

Related

how to sort array to show data of countries with covid cases in descending order instead of alphabetical order? [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 2 years ago.
this code is fetching data of Covid19 statistics using API currently its showing data of covid cases of all countries in Alphabetical order ......i want to show data in descending order i.e country with more cases should come first in table
$.ajax({
url: "https://api.covid19api.com/summary",
type: "GET",
dataType: 'JSON',
success: function(data) {
console.log(data);
console.log(data.Countries);
var sno = 1;
$.each(data.Countries, function(key, value) {
$("#country-wise").append("<tr>" +
"<td>" + sno + "</td>" +
"<td>" + value.Country + "</td>" +
"<td>" + value.NewConfirmed + "</td>" +
"<td>" + value.NewDeaths + "</td>" +
"<td>" + value.NewRecovered + "</td>" +
"<td>" + value.TotalConfirmed + "</td>" +
"<td>" + value.TotalDeaths + "</td>" +
"<td>" + value.TotalRecovered + "</td>" +
"</tr>");
sno++;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="country-wise"></table>
Use the sort method of Array.
$.ajax({
url: "https://api.covid19api.com/summary",
type: "GET",
dataType: 'JSON',
success: function(data) {
console.log(data);
console.log(data.Countries);
data.Countries.sort((a, b) => b.TotalConfirmed - a.TotalConfirmed);
var sno = 1;
$.each(data.Countries, function(key, value) {
console.log(key + ":" + value);
$("#country-wise").append("<tr>" +
"<td>" + sno + "</td>" +
"<td>" + value.Country + "</td>" +
"<td>" + value.NewConfirmed + "</td>" +
"<td>" + value.NewDeaths + "</td>" +
"<td>" + value.NewRecovered + "</td>" +
"<td>" + value.TotalConfirmed + "</td>" +
"<td>" + value.TotalDeaths + "</td>" +
"<td>" + value.TotalRecovered + "</td>" +
"</tr>");
sno++;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="country-wise"></table>

How to add a row in every 3 rows in table javascript

I create table with print out data from database like this:
here the JS and HTML.
JS
function initDataTableSaldoRek1() {
showLoadingCss()
$.ajax({
url: baseUrl + "api_dashboard/get_ivest",
dataType: 'JSON',
type: "GET",
success: function (res) {
var data = res.return;
$("#date").html(data[0].TANGGAL);
$('#table-invest tbody').empty();
$.each(data, function (key, val) {
var html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD,2,".",",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR,2,".",",") + "</td>" +
"</tr>";
$('#table-invest tbody').append(html);
});
hideLoadingCss()
},
});
}
HTML
<div class="view-table" >
<table id="table-invest" class="table table-bordered">
<thead>
<tr>
<th style="background-color: #67a2d8" width="12.5%">DATE</th>
<th style="background: #67a2d8" width="12.5%">TYPE OF PAYMENT</th>
<th style="background: #67a2d8" width="12.5%">EUR</th>
<th style="background: #67a2d8" width="12.5%">USD</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
and i want add a row every 3 rows that sum column 2 & 3 as below .
Everybody in here have ever experience to create table as below before in JavaScript?
Thank you..
Just make a check on each third row, since the $.each callback provides an index value.
function initDataTableSaldoRek1() {
showLoadingCss()
$.ajax({
url: baseUrl + "api_dashboard/get_ivest",
dataType: 'JSON',
type: "GET",
success: function (res) {
var data = res.return;
$("#date").html(data[0].TANGGAL);
let html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD, 2, ".", ",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR, 2, ".", ",") + "</td>" +
"</tr>";
$('#table-invest tbody').append(html);
$('#table-invest tbody').empty();
$.each(data, function (key, val) {
if ((key+1) % 3 === 0 ){
html = `<tr><td>TOTAL</td></tr> ${html}`;
}else{
return html;
}
});
hideLoadingCss()
},
});
}
You can simply use a counter, when this counter reaches the amount of rows you want, add the "total" row and reset the counter.
Also, keep track of the total value (I don't know which total you want to calculate, so it is up to you this part), inside the if to check the counter, reset this total too.
Something like this:
let counter = 0;
let sumTotal = 0;
$.each(data, function(key, val) {
var html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD, 2, ".", ",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR, 2, ".", ",") + "</td>" +
"</tr>";
sumTotal = 0;//USE YOUR LOGIC TO CALCULATE AND INCREASE TOTAL
$('#table-invest tbody').append(html);
counter++;
//check if it is the moment to add the new row total
if (counter == 3){
let newRow = "<tr>" +
"<td>Total: " + sumTotal + "</td>" +
"</tr>";
$('#table-invest tbody').append(newRow);
counter = 0;
sumTotal = 0;
}
});

HTML button onclick function not working with jQuery variable as argument

success: function(jsonresponse) {
data = JSON.stringify(jsonresponse);
$.each(JSON.parse(data), function (index, item) {
var Id=item.id;
var JobId=item.JobId;
var eachrow = "<tr>"
+ "<td>" + item.id + "</td>"
+ "<td>" + item.JobId + "</td>"
+ "<td>" + item.UserId + "</td>"
+ "<td>" + item.updatedAt + "</td>"
+ "<td>" + "<button onclick='myFunction(JobId,Id, \"accepted\")' class='btn btn-success btn-block'>Reject</button>" + "</td>"
+ "<td>" + "<button onclick='myFunction(JobId,Id, \"rejected\")' class='btn btn-success btn-block'>Reject</button>" + "</td>"
+ "</tr>";
$('#tbody2').append(eachrow);
});
},
myFuntion(JobId,Id,\"accepted\") does not works with variable as parameter but when manually added then the function works, like myFuntion(1,3,\"accepted\").
Problem : You are not concatenating the JobId & Id in your HTML Code?
Solution :
Properly concatenate your JobId & Id variables in your HTML code and you will be good to go as :
success: function(jsonresponse) {
data = JSON.stringify(jsonresponse);
$.each(JSON.parse(data), function (index, item) {
var Id=item.id;
var JobId=item.JobId;
var eachrow = "<tr>"
+ "<td>" + item.id + "</td>"
+ "<td>" + item.JobId + "</td>"
+ "<td>" + item.UserId + "</td>"
+ "<td>" + item.updatedAt + "</td>"
+ "<td>" + "<button onclick='myFunction("+JobId+","+Id+", \"accepted\")' class='btn btn-success btn-block'>Reject</button>" + "</td>"
+ "<td>" + "<button onclick='myFunction("+JobId+","+Id+", \"rejected\")' class='btn btn-success btn-block'>Reject</button>" + "</td>"
+ "</tr>";
$('#tbody2').append(eachrow);
});
},

How to empty the data inside tbody using jquery?

I want to empty the data inside tbody, I tried:
$("#detail_tbody").html("");
$("#detail_tbody").empty();
but the result is that the current page is cleared.
When i click the next page,the data will show again.How can i empty all of them?
<table id="detail_table">
<tr align="center">
<th style="display: none;"></th>
<th width="100px">1</th>
<th width="130px">2</th>
<th width="130px">3</th>
<th width="130px">4</th>
<th width="130px">5</th>
<th width="130px">6</th>
<th width="130px">7</th>
</tr>
<tbody id="detail_tbody"></tbody>
</table>
The js is :
for (var i = 0; i < productTradeDetail_list.length; i++) {
productTradeDetail_listobj = productTradeDetail_list[i];
p += "<tr align=\"center\">" +
"<td style='display: none;'>" + i + "</td>" + //
"<td>" + productTradeDetail_listobj.procode + "</td>" +
"<td>" + productTradeDetail_listobj.proname + i + "</td>" +
"<td>" + productTradeDetail_listobj.tradename + "</td>" +
"<td>" + productTradeDetail_listobj.confirmatm + "</td>" +
"<td>" + productTradeDetail_listobj.confirmvol + "</td>" +
"<td>" + productTradeDetail_listobj.statename + "</td>" +
"<td>" + productTradeDetail_listobj.tradedata + "</td></tr>";
}
$("#detail_tbody").empty();
$("#detail_tbody").append(p);
page = new Page(5, "detail_table", "detail_tbody");
$("#tradeDetail_pageLabel").val(page.pageIndex + 1 + "/" + page.pageCount);
ADD:I have two response,i need clear current data of response and show another when i change into next response.

table json data returning undefined using jQuery

Hi I'm stumped as to why the data in my table is returned undefined. I think I'm close.
Please check out my jsfiddle:
$(document).ready(function() {
$.getJSON( "http://www.corsproxy.com/dvl.thomascooper.com/data/json_return.json", function( data ) {
//static table head
$('table.stats').append("<th>" + "</th>" + "<th>" + "Date" + "</th>" + "<th>" + "Brand" + "</th>" + "<th>" + "Author" + "</th>" + "<th>" + "Title" + "</th>" + "<th>" + "Posts" + "</th>" + "<th>" + "Exposure" + "</th>" + "<th>" + "Engagement" + "</th>");
//loop through json data
$.each(data.data.rows,function( i, val ){
//+1 to number each row starting at 1
var rowNum = i + 1;
//create table rows and cell and populate with data
$('table.stats').append( "<tr>" + "<td>" + rowNum + "</td>" + "<td>" + val.date + "</td>" +"<td>" + val.brand_id + "</td>" + "<td>" + val.author + "</td>" + "<td>" + val.title + "</td>" + "<td>" + val.posts + "</td>" + "<td>" + val.reach + "</td>" + "<td>" + val.interaction + "</td>" + "</tr>");
});
});
});
fiddle: http://jsfiddle.net/tommy6s/eLbq2wvh/
$.each(data.data.rows,function( i, val ) {
Here, val is not object (Your data told me that)
So you could not access property that undefined like this: val.date
I think, here is what you want:
$(document).ready(function() {
$.getJSON( "http://www.corsproxy.com/dvl.thomascooper.com/data/json_return.json", function( data ) {
//static table head
$('table.stats').append("<th>" + "</th>" + "<th>" + "Date" + "</th>" + "<th>" + "Brand" + "</th>" + "<th>" + "Author" + "</th>" + "<th>" + "Title" + "</th>" + "<th>" + "Posts" + "</th>" + "<th>" + "Exposure" + "</th>" + "<th>" + "Engagement" + "</th>");
//loop through json data
$.each(data.data.rows,function( i, val ){
//+1 to number each row starting at 1
var rowNum = i + 1;
//create table rows and cell and populate with data
$('table.stats').append( "<tr>" + "<td>" + rowNum + "</td>" + "<td>" + val[0].value + "</td>" +"<td>" + val[1].value + "</td>" + "<td>" + val[2] + "</td>" + "<td>" + val[3].label + "</td>" + "<td>" + val[4].values[0] + "</td>" + "<td>" + val[5].values[0] + "</td>" + "<td>" + val[6].values[0] + "</td>" + "</tr>");
});
});
});
If you look at the returned json - rows is an array of arrays not an array of objects.. You failed to take this into consideration.
$.each(data.data.rows[0],function( i, val ){
Also you are trying to access the value of the data by its value instead of by its key.
"<td>" + val.field + "</td>" +"<td>" + val.type + "</td>"
Checkout this jsbin for example
You are trying to reference the data as if it were:
rows: [ { date: '', brand_id: '', author: '', etc }, next set of fields]
What you are actually getting is:
rows: [ [ object with field data, object with field data, etc], another array of field data objects, etc]
Here is a beginning to a script that will be flexible in how things will be returned. I've left out many of the cases you'll need to deal with:
//loop through json data
$.each(data.data.rows,function( i, val ){
//+1 to number each row starting at 1
var rowNum = i + 1, fields = {};
// Find fields
$.each(val, function(j, fieldData) {
if(typeof fieldData == 'string') {
fields.author = fieldData;
} else if(fieldData.field == 'title') {
fields.title = fieldData.label;
} else {
fields[fieldData.field] = fieldData.value;
}
});
//create table rows and cell and populate with data
$('table.stats').append( "<tr>" + "<td>" + rowNum + "</td>" + "<td>" + fields.date + "</td>" +"<td>" + fields.brand_id + "</td>" + "<td>" + fields.author + "</td>" + "<td>" + fields.title + "</td>" + "<td>" + fields.posts + "</td>" + "<td>" + fields.reach + "</td>" + "<td>" + fields.interaction + "</td>" + "</tr>");
});

Categories

Resources