Ajax - json, failing to create table - javascript

Trying to get data from https://api.quarantine.country/api/v1/summary/latest However my table isn't getting built.
My HTML table
<tr class="table"></tr>
<th>Contry name</th>
<th>Total infected</th>
<th>Recovered</th>
</tr>
</thead>
<tbody id="myTable">
</tbody>
My script
<script>
var myArray = []
$.ajax({
method: 'GET',
url: 'https://api.quarantine.country/api/v1/summary/latest',
success: function(response) {
myArray = response.data.regions
console.log(myArray)
buildTable(myArray)
}
})
function buildTable(data) {
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++) {
var row = `<tr>
td${data[i].name}td
td${data[i].total_cases}td
td${data[i].recovered}td
</tr>`
table.innerHTML += row
}
}
</script>
I get data.regions on my console however, it seems like im unable to read through the objects using the buildTable() function. Cant figure out why.

data is not array it is an object so need to get all keys of the object
var myArray = []
$.ajax({
method: 'GET',
url: 'https://api.quarantine.country/api/v1/summary/latest',
success: function(response) {
myArray = response.data.regions
// console.log(myArray)
buildTable(myArray)
}
})
function buildTable(data) {
var table = document.getElementById('myTable');
Object.keys(data).forEach(function (item) {
var row = `<tr>
<td>${data[item].name}</td>
<td>${data[item].total_cases}</td>
<td>${data[item].recovered}</td>
</tr>`
table.innerHTML += row
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr class="table">
<th>Contry name</th>
<th>Total infected</th>
<th>Recovered</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Related

How to pull a API Response data into a HTML Table

i'm trying to pull data from a response i'm getting on a Google Workspace API request to a HTML table, the response i'm getting is an array that is being store at an HTML element every time I made the request. Here's my code for it:
function execute() {
return gapi.client.directory.users.list({"domain": "mydomain", "maxResults": 450})
.then(function(response) {
let t = document.querySelector("#tabela")
let data = []
console.log(response)
response.result.users.forEach((user)=> {
data.push(user)
// console.log("Email"+ user.primaryEmail)
// console.log("Email"+ user.lastLoginTime)
SheetDB.write('https://sheetdb.io/api/v1/81m3qdtu47hra', { sheet: 'Sheet1', data: {email: '${user.primaryEmail}' , login: '${user.lastLoginTime}'}}).then(function(result){
console.log(result);
}, function(error){
console.log(error);
});
})
console.log(data)
let td = data.reduce((acc, user)=>{
acc += `<tr>${user.lastLoginTime}</tr>`
return acc
},"")
t.innerHTML = td
console.log("O result é:", td)
},
function(err) { console.error("Execute error", err); });`
and then, my code which is not working to populate my html table with it:
<table class="table table-striped">
<tr class="bg-info">
<th>E-mail</th>
<th>Last Login Time</th>
<th>Status</th>
<th>Permissions</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
<script>
var myArray = document.querySelector("#tabela")
buildTable(myArray)
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${user.primaryEmail}</td>
</tr>`
table.innerHTML += row
}
}
what am I doing wrong?
The buildTable function requires an array as the argument to the function whereas you are passing the entire myTable element as the argument on the second line in your script tag. That is why the for loop never gets executed since data.length would be undefined. Pass the array of data from the API to the function and you should be good to go.

Populate Table Content with Data From Ajax

I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);

How to use Jquery Datatable with AngularJs to export table

I am working on angular website where I need to export table's data to pdf.
I want to use jQuery datatables for it as it alse add some more features like paging,searching and sorting, but getting this error "Error: [$injector:unpr]" on browser's console, even I am not sure using ng-table will make it to datatable or not.
I have also tried using jquery plugin pdfmake but it only make signle page pdf and failed if table have larger data.
Please help and TIA.
Html :-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.min.js"></script>
<table id="myYealyGrid" ng-class="myYealyGridClass" class="table table-responsive gridtable" ng-table="yearly_Table">
<thead>
<tr>
<th>Customer Name</th>
<th>Year</th>
<th>Total Amount($)</th>
</tr>
</thead>
<tbody>
<tr ng-show="YearlyReport.length !=0" ng-repeat="reportrow in YearlyReport" ng-init="setTotal(reportrow)">
<td>{{reportrow.CustomerName}}</td>
<td>{{reportrow.Month}}</td>
<td>{{reportrow.TotalAmount}}</td>
</tr>
<tr ng-show="YearlyReport.length ==0">
<td><small class="nodata">No data found.</small></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot>
<tr ng-show="YearlyReport.length !=0" class="bg-warning">
<td class="td-font-bold-custm">Total</td>
<td></td>
<td class="td-font-bold-custm">{{gridTotalAmount | number:2}}</td>
</tr>
</tfoot>
</table>
AngularJs:-
var appKitchenOrderReport = angular.module("myKitchenOrderReportApp", ['ngTable']);
appKitchenOrderReport.controller("myKitchenOrderReportCntrl", function ($scope, $window, $timeout, myKitchenOrderReportService, ngTableParams) {
var getData = myKitchenOrderReportService.SearchData($scope.CustomerName, $scope.Year);
getData.then(function (kitchenreportdata) {
var yearlyGridData = kitchenreportdata.data.OrderYearlyReport;
$scope.yearly_Table = new ngTableParams({
page: 1,
count: 10
}, {
total: $scope.yearlyGridData.length,
getData: function ($defer, params) {
$scope.YearlyReport = $scope.yearlyGridData.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.YearlyReport);
}
});
}, function () {
alert('Error in getting data');
});
});
appKitchenOrderReport.service("myKitchenOrderReportService", function ($http) {
this.getKitchenOrderReportData = function () {
var response = '';
return $http.get("GetOrderReport"); };
this.SearchData = function (CustomerName, Year)
{
var GetParams = new Object();
GetParams.CustomerName = CustomerName;
GetParams.Year = Year
var response = $http({
method: "post",
url: "GetOrderReport",
data: '{model: ' + JSON.stringify(GetParams) + '}',
});
return response;
}
});
you can Use $('#myYealyGrid').DataTable(); to initialize your datatable .
But Use just befor , when you Put data into the HTML table .
It will automatically initialize your Datatable.
Try it and let me know is it working or not .

Unable to add row in the middle of jQuery datatables(with FIDDLE)

I am trying to add new rows to the table using the rows.add() function in the DataTables API. The data is coming from the server using AJAX call.
Here is an example to work upon - FIDDLE
My Table Structure is follows:
<table id="myTable">
<thead>
<th>
Id
</th>
<th>
Name
</th>
<th>
Designation
</th>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Number
</td>
<td>
#item.Name
<img id="imgA" onclick="AddNewRows();" class="iterationChild" src="#Url.Content("~/Images/plus.png")" alt="expand/collapse" />
</td>
<td>
#item.Designation
</td>
</tr>
}
</tbody>
</table>
Corresponding Javascript function:
function AddNewRows() {
$.ajax({
type: 'GET',
url: '#Url.Action("NewRows", "Home")',
dataType: "json",
async: true,
success: function (data) {
var table = $('#myTable').DataTable();
for (var i = 0, l = data.length; i < l; i++) {
//how to add it just after the current row clicked
table.row.add([
data[i].Number,
data[i].Name,
data[i].Designation
]).draw();
}
},
error: function (result) {
alert('error');
}
});
}
I want to be able to add the new row after the row which is clicked. Here it is adding at the end of the table(last rows).
Assuming every row as a unique id, try passing the current row clicked id into your function as a parameter. Example:
function AddNewRows(id) {
var my_row = document.getElementById(id);
...

Hide "No data available in table" message when data is present

This is my table , I get the data list using json and populate this table,
<table id="tblClaimSearch" class="display responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="ChkboxClaimHeader" name="ChkboxClaimHeader" value="false"></th>
<th>Claim #</th>
<th>Client Name</th>
<th>Amount</th>
<th>Deduction</th>
<th>Type</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My jquery which has Json result, I get the result and append rows to table body based on my data,
$(document).ready(function () {
$.ajax({
url: '#Url.Action("ClaimResultTest", "Claims")',
data: { seacrhClaimNumber: claimNumberToBeSearched },
type: 'POST',
success: function (data) {
var dataClaims = data.Claims;//This has the complete list
for (i = 0; i < dataClaims.length; i++) {
alert(dataClaims[i].ClaimNumber);
$("#tblClaimSearch").find('tbody')
.append($('<tr>')
.append($('<td><input type="checkbox">'))
.append($('<td>').text(dataClaims[i].ClaimNumber))
.append($('<td>').text(dataClaims[i].Client))
.append($('<td>').text(dataClaims[i].Amount))
.append($('<td>').text(dataClaims[i].Deduction))
.append($('<td>').text(dataClaims[i].Type))
.append($('<td>').text(dataClaims[i].Status))
)
}
}
});
});
The problem is when there is no data, I have a row displaying "No data available in table"..And even when there is data appended I still have first row as "No data available in table"..How do I hide this message row when new rows with data have been added??And secondly even though I have 16 entries it still shows "Showing 0 of 0 entries"?.What am I doing wrong?..
try this:-
$(document).ready(function () {
$.ajax({
url: '#Url.Action("ClaimResultTest", "Claims")',
data: { seacrhClaimNumber: claimNumberToBeSearched },
type: 'POST',
success: function (data) {
$("#tblClaimSearch").find('tbody').empty(); //add this line
var dataClaims = data.Claims;//This has the complete list
for (i = 0; i < dataClaims.length; i++) {
alert(dataClaims[i].ClaimNumber);
$("#tblClaimSearch").find('tbody')
.append($('<tr>')
.append($('<td><input type="checkbox">'))
.append($('<td>').text(dataClaims[i].ClaimNumber))
.append($('<td>').text(dataClaims[i].Client))
.append($('<td>').text(dataClaims[i].Amount))
.append($('<td>').text(dataClaims[i].Deduction))
.append($('<td>').text(dataClaims[i].Type))
.append($('<td>').text(dataClaims[i].Status))
)
}
}
});
});

Categories