table json data returning undefined using jQuery - javascript

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>");
});

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>

JSON Formatting Issue?

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
}
]
}

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);
});
},

one ajax loop with 2 outputs error innerHTML

Having a few issues trying to get this function output to an ajax table (working fine) and an input box called connectsList1.
i cannot get it to spit out into the input box without error, the error is
Uncaught TypeError: Cannot set property 'innerHTML' of null
and
connectsList1 is not defined
function getConnections(txt1) {
func_getConnections(
function (response) {
var sortorder = txt1;
var arr = response;
var i;
var Count;
var mCount;
var oCount;
var out =
"<thead>"
for (i = 0; i < arr.length; i++) {
out +=
"<tr>" +
"<tbody>" +
"<tr class=\"" + ReturnValuesAsColor(arr[i].o, arr[i].m, arr[i].server_proc) + "\">" +
"<td>" + arr[i].id + "</td>" +
//"<td>" + arr[i].user_id + "</td>" +
"<td>" + arr[i].user_name + "</td>" +
"<td>" + arr[i].workstation_name + "</td>" +
"<td>" + (!!arr[i].ip_address ? arr[i].ip_address : '') + "</td>" +
"<td>" + formatDateTime(arr[i].connect_date, 'datelongtime') + "</td>" +
"<td>" + formatDateTime(arr[i].refresh_date, 'datelongtime') + "</td>" +
"<td>" + (!!arr[i].app_ver ? arr[i].app_ver : '') + "</td>" +
"<td>" + (!!arr[i].app_date ? formatDateTime(arr[i].app_date, 'shortdate') : '') + "</td>" +
"<td>" + Messages_flag(arr[i].get_messages_flag) + "</td>" +
"<td>" + FixNumbers(arr[i].message_type_flags) + "</td>" +
//"<td>" + arr[i].o + "</td>" +
//"<td>" + arr[i].m + "</td>" +
"<td>" + arr[i].group_name + "</td>" +
//"<td>" + arr[i].server_proc + "</td>" +
"<td> <button id=\"DelImg1\" type=\"button\" name=\"btnsubmit\" class=\"ui-button ui-widget ui-state-default ui-corner-all\" onclick=\"clearText('<%= result.ClientID%>'); CopyId(" + arr[i].id + "); return Message(" + arr[i].id + ")\" >Delete</button> </td>" +
"</tr>" +
"</tbody>";
mCount = 0
if (arr[i].m != 0) {
mCount += 1;
} else if (arr[i].o != 0) {
oCount += +1;
} else if (arr[i].o == 0 & arr[i].m == 0) {
Count += 1;
}
document.getElementById("dtBody1").innerHTML = out;
document.getElementById('ConnectsList1').innerHTML = out;
ConnectsList1 = " Connection list: " & Count + oCount + mCount & " connection(s) Main Application : " & Count & " Online : " & oCount & " Mobile : " & mCount;
}})};
Any help or advice welcome, still learning ajax myself
document.getElementById("dtBody1") can not find any tag with id dtBody1. Make sure your HTML has an element with that ID.
And remember to declare the ConnectsList1 variable to avoid the second error.

Use image in for each but with different onclicks

I'm making a table with a for each loop.
In every row i want to add a image but with different onclicks.
This is what i got now. All the "onclicks" are edited to the last for each round.
function cart(){
count = readCookie("count");
tableRow = "";
for (i = 1; i <= count; i++){
item = "item" + i;
Cookie = readCookie(item);
if (!(Cookie == null)){
row = new Array();
row = Cookie.split("|");
tableRow += "<tr>"
+ "<td>" + row[0] + "</td>"
+ "<td>" + row[1] + "</td>"
+ "<td>" + row[2] + "</td>"
+ "<td>" + row[3] + "</td>"
+ "<td>" + row[4] + "</td>"
+ "<td>" + row[5] + "</td>"
+ "<td>" + row[4] * row[5] + "</td>" + "<td>"
+ "<a href=''><img src='img/delete.png' onclick='editCart(item);'></a>"
+ "</td>" + "</tr>";
}
}
document.write(tableRow);}
I know cookies are not the best way to do it but it's a school assignment.
Thats why even if you only like to give a hint i still would appreciate it.
"<a href=''><img src='img/delete.png' onclick='editCart(item);'></a>"
Every onclick call will be the same.
"<a href=''><img src='img/delete.png' onclick='editCart(\""+item+"\");'></a>"
This will generate the outputlink dynamically.

Categories

Resources