Write response from API to HTML - javascript

I have an API response like this:
{
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}
I want to write the total value from the response above, 5, to my HTML. When I create the js file to get the response the result in HTML is empty.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>
$(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(data) {
$.each(data, function(value) {
//append each row data to datatable
var row = value.total
$('#total').append(row);
});
}
})
})
Do you know how to show the total that I want from the API in HTML? Thank you

You don't need an each() loop here as the response is a single object, not an array. As such you can access the data.value and set it as the text() of #total, like this:
$(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(response) {
var total = response.data.total;
$('#total').text(total);
}
})
})

Use innerHTML to insert value
var a= {
"status": 200,
"message": "OK",
"data": {
"total": 5
}
};
document.querySelector('#total').innerHTML=a.data.total
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>

/* $(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(response) {
var total = 0;
for (var i = 0; i < response.length; i++) {
total = total + response[i].data.total;
}
$('#total').text(total);
}
})
}) */
// for ex.: -
const data = [{
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}, {
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}, {
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}];
var total = 0;
for (var i = 0; i < data.length; i++) {
total = total + data[i].data.total;
}
$('#total').text(total);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>

try this I think it should be work
$('#total').append(`<p>${row}</p>`)
{
"status": 200,
"message": "OK",
"data": {
"total": 5
}
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<div class="inner">
<h3 id="total"></h3>
<p>Total</p>
</div>
$(function() {
$.ajax({
url: 'https://api-url',
type: 'GET',
dataType: 'json',
success: function(data) {
var row = data.data.total
$('#total').text(row);
});
}
})
})

Related

trying check if sql table value already exists before inserting

I have a basic table with an id column and a location name column. I also have an html form where a user can insert a new location into the table. Before inserting I want to check if my locations table already includes a location name and if it does exist I want to alert the user. If not it will be inserted into the table. First I query the locations table and then I try to use an if statement to see if the input value already matches a location name in my table. But I can't get it to work. My insert code works fine on it's own but I just can't get the conditions working. Any help would be greatly appreciated.
// add a new location
$("#btn-locationAdd").on("click", function() {
var addLocationName = $("#addLocationName");
$.ajax({
url: 'libs/php/getAllLocations.php',
method: 'POST',
dataType: 'json',
success: function (result) {
for (let i = 0; i < result.data.length; i++) {
if (result.data[i].name === addLocationName.val()) {
alert('This location aready exists')
} else {
$.ajax({
url: 'libs/php/insertLocation.php',
method: 'POST',
dataType: 'json',
data: {
addLocationName: addLocationName.val(),
},
success: function (result) {
$("#addNewLocationModal").modal('hide');
const newLocation = $("#alertTxt").html('New Location Record Created');
alertModal(newLocation);
}
});
}
this is the array I get after I query the locations table and get all locations in the table:
{
"status": {
"code": "200",
"name": "ok",
"description": "success",
"returnedIn": "1.5790462493896E-6 ms"
},
"data": [
{
"id": "1",
"name": "London"
},
{
"id": "2",
"name": "New York"
},
{
"id": "3",
"name": "Paris"
},
{
"id": "4",
"name": "Munich"
},
{
"id": "5",
"name": "Rome"
}
]
}
my html:
<!-- Add Location Modal -->
<div id="addNewLocationModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title">Add New Location</h2>
</div>
<div class="modal-body">
<input type="text" class="form-control" placeholder="Location Name" id="addLocationName"><br>
</div>
<div class="modal-footer">
<input type="button" id="btn-locationAdd" value="Add Location" class="btn btn-success">
<input type="button" id="btn-addLocationCancel" value="CANCEL" data-bs-dismiss="modal" class="btn btn-secondary">
</div>
</div>
</div>
</div>
$("#btn-locationAdd").on("click", function () {
var addLocationName = $("#addLocationName");
$.ajax({
url: 'libs/php/getAllLocations.php',
method: 'POST',
dataType: 'json',
success: function (result) {
let existed = false;
for (let i = 0; i < result.data.length; i++) {
if (result.data[i].name === addLocationName.val()) {
existed = true
break
}
}
if(existed){
alert('This location aready exists')
return
}
$.ajax({
url: 'libs/php/insertLocation.php',
method: 'POST',
dataType: 'json',
data: {
addLocationName: addLocationName.val(),
},
success: function (result) {
$("#addNewLocationModal").modal('hide');
const newLocation = $("#alertTxt").html('New Location Record Created');
alertModal(newLocation);
}
});
}
})
})

JTable Not Populated

My table is loading with no data...this is how I have the javascript set-up to handle it....
<script type="text/javascript">
$(document).ready(function () {
$('#btnEmployeeTableLoad').click(function () {
$('#EmployeeTable').jtable({
paging: true,
pageSize: 10,
sorting: true,
defaultSorting: 'employeeName ASC',
actions: {
listAction: 'https://localhost:44328/api/employee-information',
//deleteAction: '/Home/DeletePerson',
//updateAction: '/Home/UpdatePerson',
//createAction: '/Home/CreatePerson'
},
fields: {
employeeName: {
title: 'employeeName',
width: '35%'
},
employeeAddress: {
title: 'employeeAddress',
width: '15%'
},
employeeManager: {
title: 'employeeManager',
width: '15%'
},
prevExperience: {
title: 'prevExperience',
width: '15%'
}
}
});
$('#EmployeeTable').jtable('load');
});
});
</script>
both my ListData and ListData.Count show 752 rows so I know the data is being retreived from server
return Json(new { Result = "OK", Records = ListData, TotalRecordCount = ListData.Count });
EDIT
This is what the Network tab shows in my browser:
{result: "OK",…}
records: [{employeeName: "Employee Name 1", employeeAddress: "Test Address 1", employeeManager: "Test Manager 1", prevExperience: "No"},…]
result: "OK"
totalRecordCount: 757
EDit 2
These are the libraries i'm including
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"></style>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.6.0/js/buttons.print.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jtable#2.6.0/lib/jquery.jtable.min.js"></script>
<link href="https://cdn.datatables.net/buttons/1.6.0/css/buttons.dataTables.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/jtable#2.6.0/lib/themes/metro/blue/jtable.css" rel="stylesheet">
The problem is with the API server for sure.
Does your API support POST calls? Because as per jtable docs.
If you defined listAction as a URL string, then, when you use the load
method, jTable makes an AJAX POST to this URL address to get list of
records
Also make sure the response JSON response must match the structure.
{
"Result": "OK",
"Records": [
{
"prevExperience": 2,
"employeeName": "Douglas Adams",
"employeeManager": "Simon",
"employeeAddress": "Washigton"
}
]
}
If you want to make a GET call, listAction should be a function instead of a string
actions: {
listAction: function () {
console.log("Loading from custom function...");
return $.Deferred(function ($dfd) {
$.ajax({
url: "https://localhost:44328/api/employee-information/",
type: 'GET',
dataType: 'json',
success: function (data) {
console.log("Success");
$dfd.resolve(data);
},
error: function () {
console.log("Error");
$dfd.reject();
}
});
});
}
}
In your case, the output JSON has structure {result: "OK", records: []}
You need to transform it to {Result: "OK", Records: []} for jtable to work. This can be done in the ajax call success handler like below.
actions: {
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: 'https://localhost:44328/api/employee-information?' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'GET',
dataType: 'json',
success: function (data) {
$dfd.resolve({ Records: data.records, Result: data.result, TotalRecordCount: data.totalRecordCount });
},
error: function () {
$dfd.reject();
}
});
});
}
}
Codepen link with your code.
https://codepen.io/nithinthampi/pen/zYYwgLq
Dummy server with GET.
https://RoundPungentProject.nithinthampi.repl.co

import Json to html (table)

im trying to import a json url to html in a table. The problem is when i get the data i get 25 rows i get this on the web console: Object { data: Array[25], paging: Object } I also have the following code which is designed for only one row i guess .And i understand i have Loop over each object, appending a table row with the relevant data of each iteration. The problem is i don´t how to do it, i´m not an expert . Thank you for your help!
This is the data i get on the json url :
{
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
And this my code
<body>
<input type="text" class="txtPagina">
<button class="btnBuscar">Buscar</button>
<table class="tabla" border='1'>
<tr>
<td>created time</td>
<td>permalink url</td>
<td>id</td>
<td>Shares Count</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.btnBuscar').on('click', function (){
var pagina = $('.txtPagina').val();
//Ajax
$.ajax({
type: "GET",
dataType: "json",
url: "https://graph.facebook.com/"+pagina+"/feed?fields=created_time,permalink_url,id,shares& access_token=mytoken",
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
error: function (){
console.log("Error");
}
});
});
});
</script>
</body>
</html>
success: function(data){
console.log(data);
$('.tabla').append("<tr><td>"+data.created_time+"</td><td>"+data.permalink_url+"</td><td>"+data.id+"</td><td>"+data.shares+"</td></tr>");
},
should be
success: function(data){
$.each(data.data, function(i, d){
var s = d.shares ? '<td>'+d.shares.count+'</td>' : '';
$('.tabla').append('<tr><td>'+d.created_time+'</td><td>'+d.permalink_url+'</td><td>'+d.id+'</td>'+s+'</tr>');
});
},
function create(t,attr,parent_node,innerdata){
var dom = document.createElement(t)
for(key in attr){
dom.setAttribute(key,attr[key])
}
dom.innerHTML = innerdata;
parent_node.appendChild(dom)
return dom;
}
window.onload = function () {
var d = {
"data": [
{
"created_time": "2017-11-10T01:24:47+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539014319521507",
"id": "949007375188874_1539014319521507"
},
{
"created_time": "2017-11-10T01:23:37+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1539013649521574",
"id": "949007375188874_1539013649521574"
},
{
"created_time": "2017-11-09T23:59:15+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538951229527816",
"id": "949007375188874_1538951229527816",
"shares": {
"count": 20
}
},
{
"created_time": "2017-11-09T23:32:30+0000",
"permalink_url": "https://www.facebook.com/DBZSFANSOFICIAL2/posts/1538935439529395",
"id": "949007375188874_1538935439529395"
},
]
}
var tb= document.getElementById('inputTable')
f = {"created_time":1,"permalink_url":1,"id":1,"shares":1}
d['data'].forEach(function(val){
tr_dom = create('tr',{},tb,'')
Object.keys(f).forEach(function(tr){
if(tr in val){
if('shares' == tr)
td_dom = create('td',{},tr_dom,val[tr]['count'])
else
td_dom = create('td',{},tr_dom,val[tr])
}else
td_dom = create('td',{},tr_dom,'')
})
})
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table border='1'>
<thead>
<th>Create Time</th>
<th>permalink_url</th>
<th>id</th>
<th>Share</th>
</thead>
<tbody id="inputTable">
</tbody>
</table>
</body>
</html>

How to print JSON objects correctly after successful JSONP request with Javascript

How to correctly parse/print JSON "scores" objects into demo div (I need just away, home and score data of each)?
My JSON query look like this (code below is also working)
{ "query": { "count": 18, "created": "2016-09-07T06:10:58Z", "lang": "fi", "results": { "json": [ { "scores": { "away": "ESBJERG ENERGY", "home": "EV ZUG", "match_type": "fin", "status": "fin", "matchId": "1311357", "score": "3-2", "image": "EUROPE (IIHF)" } }, { "scores": { "away": "HC DAVOS", "home": "ROUEN", "match_type": "fin", "status": "fin", "matchId": "1311356", "score": "2-3", "image": "EUROPE (IIHF)"}}]}}}
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="results"></div>
<div id="resultsshouldbelikethis">
EV ZUG - ESBJERG ENERGY (3-2)<br>
ROUEN - HC DAVOS (2-3)<br>
...and so on
</div>
<script>
jQuery.support.cors = true;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20scores%20from%20json%20where%20url%3D%22http%3a%2f%2fmobile.xscores.com%2fm_livescore%3fsport%3d4%26match_type%3dlive%26match_date%3d2016-09-06%26startPos%3d0%26endPos%3d5000%22%20limit%2050&format=json",
type: "GET",
timeout: 3000,
dataType: "jsonp",
success: function(parsa) {
document.getElementById("results").innerHTML =
parsa.query.scores;
console.log(parsa);
},
});
</script>
Console log works well but how to print results nicely into a div? "parsa.query.scores;" just results undefined.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery 2.1.4.min.js"></script>
</head>
<body>
<div id="results"></div>
<div id="resultsshouldbelikethis">
EV ZUG - ESBJERG ENERGY (3-2)<br>
ROUEN - HC DAVOS (2-3)<br>
...and so on
</div>
<script>
jQuery.support.cors = true;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20scores%20from%20json%20where%20url%3D%22http%3a%2f%2fmobile.xscores.com%2fm_livescore%3fsport%3d4%26match_type%3dlive%26match_date%3d2016-09-06%26startPos%3d0%26endPos%3d5000%22%20limit%2050&format=json",
type: "GET",
timeout: 3000,
dataType: "jsonp",
success: function(parsa) {
var news = document.getElementsById("results");
var items = parsa.query.scores;
for(var i = 0; i < items.length; i++) {
var p= document.createElement("p");
p.innerHTML = items[i].away;
news.appendChild(p);
var p = document.createElement("p");
p.innerHTML = items[i].home;
news.appendChild(p);
var p = document.createElement("p");
p.innerHTML = items[i].score;
news.appendChild(p);
}
},
});
</script>
You aren't parsing the JSON properly. Here is an example which shows the first score. You have to iterate the results to show each score.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="results"></div>
<div id="resultsshouldbelikethis">
EV ZUG - ESBJERG ENERGY (3-2)<br>
ROUEN - HC DAVOS (2-3)<br>
...and so on
</div>
<script>
jQuery.support.cors = true;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20scores%20from%20json%20where%20url%3D%22http%3a%2f%2fmobile.xscores.com%2fm_livescore%3fsport%3d4%26match_type%3dlive%26match_date%3d2016-09-06%26startPos%3d0%26endPos%3d5000%22%20limit%2050&format=json",
type: "GET",
timeout: 3000,
dataType: "jsonp",
success: function(parsa) {
document.getElementById("results").innerHTML =
parsa.query.results.json[0].scores.score;
console.log(parsa);
},
});
</script>
You need to loop each data one-by-one and add them into div.
Try this:
jQuery.support.cors = true;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20scores%20from%20json%20where%20url%3D%22http%3a%2f%2fmobile.xscores.com%2fm_livescore%3fsport%3d4%26match_type%3dlive%26match_date%3d2016-09-06%26startPos%3d0%26endPos%3d5000%22%20limit%2050&format=json"
, type: "GET"
, timeout: 3000
, dataType: "jsonp"
, success: function (parsa) {
var strHtml = '';
$.each(parsa.query.results.json, function (key, value) {
strHtml += value.scores.home + ' - ' + value.scores.away;
strHtml += '(' + value.scores.score + ')<br />';
});
document.getElementById("results").innerHTML = strHtml;
}
});
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="results"></div>
</body>

Zing Feed get data from rest api

I am getting a json data from rest api and i want to use it as input to ZingFeed.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
function getNewData()
{
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function(data){
var mem = data.mem.size/10000;
return mem/10000;
//$("#processInfo").append(data.mem.size);
//$("#processInfo").append(" ")
}
});
//return parseInt(memSize);
}
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
var tick = {};
// tick.plot0 = parseInt(10 + 900 * Math.random(), 10);
tick.plot0 = parseInt(getNewData());
//tick.plot0 = parseInt(1);
callback(JSON.stringify(tick));
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>
</html>
It is working fine when seen in firebug.The data (i.e mem in this case is really huge, so i have divided it twice before assigning it to tick.plot0).
After getting assigned to tick.plot0 .. it shows Nan when hovered over in the developer tools.
Could you help me plotting these huge values in ZingFeed Charts
Thanks in advance
The issue here is the nature of asynchronous functions in Javascript. Returning the data from AJAX doesn't work the way you've attempted above. You can read more about it here.
Here's a working solution.
I work on the ZingChart team. Let me know if you have other questions about the ZingChart library.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function (data) {
var mem = data.mem.size/10000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
}
});
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>

Categories