Zing Feed get data from rest api - javascript

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>

Related

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

Write response from API to HTML

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

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>

DataTables does not display data

I'm trying the jQuery DataTables control. The problem is that I cannot display data.
HTML is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
</head>
<script>
var d = [
{ "Id": 3, "ActivityID": 91, "OperationType": 0, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
{ "Id": 4, "ActivityID": 91, "OperationType": 4, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
{ "Id": 5, "ActivityID": 92, "OperationType": 0, "UserID": 5688, "Comments": "", "ActionDate": "2006-03-20T12:05:40.563" }
];
$(document).ready(function () {
$('#example').dataTable({
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"dataSrc": "",
"contentType": "application/json; charset=utf-8"
},
//"data": d,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
var table = $('#example').DataTable();
alert('There are' + table.data().length + ' row(s) of data in this table');
});
</script>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
If I comment out the Ajax code and uncomment the
//"data": d,
It works fine. The d variable is the JSON data that I get from the service using firefox->developer->network->xhr->response dialog.
I read many posts and I tried many things but I can't make it work.
Any help?
Thanks.
EDIT:
Service Code:
namespace JsonTest
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetData()
{
var list = ActivityHistory.GetAll(); // List<ActivityHistory>
var s = Newtonsoft.Json.JsonConvert.SerializeObject(list);
return s;
//return "{\"aaData\":" + s + "}";
}
}
}
EDIT 21/07/2015:
I've done some changes in HTML code and it's working with a little bug. While loading I see for a moment at the top of the page the headers of the table element (ActivityHistoryID, AH_ActivityID, AH_OperationType, AH_UserID, AH_Comments, AH_TimeStamp). After that it's working fine (for 60.000 rows!!!).
The new-changed code is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$.ajax({
type: "post",
url: "WebService1.asmx/getdata",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = $.parseJSON(data.d);
$('#example').DataTable({
"data": myData,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
My last hope is that I 'm using JQuery 1.10.2 instead of 1.11.1 which is in the examples of datatables site.
It 's the third day of trying and still I cannot figure it out.
EDIT 22/7/2015
That is the code that works. Far from examples.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTestWorking.aspx.cs" Inherits="JsonTest.DataTablesTestWorking" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DataTables Test</title>
<script src="Scripts/jquery-1.11.3.min.js"></script>
<link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<script src="Scripts/DataTables/jquery.dataTables.js"></script>
<link href="Content/Site.css" rel="stylesheet" />
<script>
$(document).ready(function () {
$('#example').hide();
$.ajax({
type: "POST",
url: "WebService1.asmx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#example').show();
var myData = $.parseJSON(data.d);
$('#example').DataTable({
"data": myData,
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="example" class="display">
<thead>
<tr>
<th>ActivityHistoryID</th>
<th>AH_ActivityID</th>
<th>AH_OperationType</th>
<th>AH_UserID</th>
<th>AH_Comments</th>
<th>AH_TimeStamp</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
</html>
Modify your ajax call - make it asynchronous
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"async" : false,
"contentType": "application/json; charset=utf-8"
}
Now your data will be binded only after the ajax request is completed from your service.
It worked for me.
In your server-side code , use printwriter to send the json data as a string.
PrintWriter out = resp.getWriter();
result.put("iTotalRecords", total);
result.put("iTotalDisplayRecords", totalRecordCount);
result.put("aaData", array);
resp.setContentType("text/jsonp");
out.print(result);
Or else use gson to conver your list of objects to json array
e.g.,
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(dataTableObject);
out.print(json);
NOTE : aaData needs to be set else your data will not be binded.
According to this post option contentType: 'application/json; charset=UTF-8' and type: 'POST' is indeed required to invoke an ASP.NET AJAX web method.
However, in order to send JSON-encoded parameters rather than URL-encoded parameters, you need to use ajax.data option to encode parameters into string in JSON format.
$('#example').dataTable({
"ajax": {
"url": "WebService1.asmx/GetData",
"type": "POST",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
"data": function ( d ) {
return JSON.stringify( d );
},
"dataSrc": "d",
},
"columns": [
{ "data": "Id" },
{ "data": "ActivityID" },
{ "data": "OperationType" },
{ "data": "UserID" },
{ "data": "Comments" },
{ "data": "ActionDate" }
]
});

JSP JSON with Google Charts - Line Charts

my graph didn't load up. I try to parse JSON from an JSP page to HTML page with javascript.
I don't know what is the problem. This is the details :
My HTML Page :
<!DOCTYPE html>
<html>
<head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var obj="";
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url : 'getDataGlucose.jsp',
dataType:'json',
success : function(glucoseData) {
obj = JSON.stringify(glucoseData)
alert('Pass? : '+obj);
},
error : function(xhr, type) {
alert('server error occoured')
}
});
var google_data = {
"cols": [{
"type": "number"
}, {
"type": "number"
}],
rows: []
};
for (var i = 0; i < obj.length; i++) {
google_data.rows.push({
c: [{
v: obj[i].xValue
}, {
v: obj[i].glucose
}]
});
}
var data = new google.visualization.DataTable(google_data);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {
title: 'Glucose Data Intake',
hAxis: {
title: 'Intake'
},
curveType: 'function',
vAxis: {
title: 'mmHg'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My generate JSON from JSP page :
[{"glucose":5.5,"xValue":0}, {"glucose":6.2,"xValue":1}, {"glucose":5.8,"xValue":2}, {"glucose":7,"xValue":3}, {"glucose":6,"xValue":4}, {"glucose":7.5,"xValue":5}, {"glucose":6,"xValue":6}, {"glucose":5.5,"xValue":7}, {"glucose":6,"xValue":8}, {"glucose":5.8,"xValue":9}]
Found my way out. I changed from :
obj = JSON.stringify(glucoseData);
to
obj = eval('(' + JSON.stringify(glucoseData) + ')');

Categories