Write response from JSON Array to Google Chart and HTML - javascript

I have a google chart code like below
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type');
data.addColumn('number', 'Total');
data.addRows([
['Damage', 3],
['Lost', 1]
]);
// Instantiate and draw our chart, passing in some options.
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I want to insert with json api array like below
"status": 200,
"message": "OK",
"data": [
{
"_id": {
"report_type": "robbery"
},
"report_type": "robbery",
"Counts": 11
},
{
"_id": {
"report_type": "property_damage"
},
"report_type": "property_damage",
"Counts": 39
},
{
"_id": {
"report_type": null
},
"report_type": null,
"Counts": 2
}
]
I want to change type and total in the google chart above with report_type and Counts value in api.
I have tried write code below, but the results is not coming
function drawChart() {
$.ajax({
url: "api-url",
type: "GET",
success: function (data) {
var arrReport = [['Type', 'Total']];
$.each(data, function (index, value) {
arrReport.push([value.data.report_type, value.data.Counts]);
});
var options = {
'width':400,
'height':300
};
var figures = google.visualization.arrayToDataTable(arrReport)
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(figures, google.visualization.PieChart(options));
}
});
}
Do you know where's the error from my code ?
Thank you

if the following is the json you are receiving...
"status": 200,
"message": "OK",
"data": [
{
"_id": {
"report_type": "robbery"
},
"report_type": "robbery",
"Counts": 11
},
{
"_id": {
"report_type": "property_damage"
},
"report_type": "property_damage",
"Counts": 39
},
{
"_id": {
"report_type": null
},
"report_type": null,
"Counts": 2
}
]
in the following data argument,
then you should be looping on --> data.data
and accessing the values as --> value.report_type & value.Counts
var arrReport = [['Type', 'Total']];
$.each(data.data, function (index, value) {
arrReport.push([value.report_type, value.Counts]);
});
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
var options = {
width: 400,
height: 300
};
var arrReport = [['Type', 'Total']];
var figures;
// will fail here on SO
$.ajax({
url: 'api-url',
type: 'GET'
}).done(function (data) {
drawChart(data);
}).fail(function () {
// draw with hard-coded data, for example purposes
var data = {
"status": 200,
"message": "OK",
"data": [
{
"_id": {
"report_type": "robbery"
},
"report_type": "robbery",
"Counts": 11
},
{
"_id": {
"report_type": "property_damage"
},
"report_type": "property_damage",
"Counts": 39
},
{
"_id": {
"report_type": null
},
"report_type": null,
"Counts": 2
}
]
};
drawChart(data);
});
function drawChart(data) {
$.each(data.data, function (index, value) {
arrReport.push([value.report_type, value.Counts]);
});
figures = google.visualization.arrayToDataTable(arrReport);
chart.draw(figures, options);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
NOTES:
1) you should be using the newer library loader.js
<script src="https://www.gstatic.com/charts/loader.js"></script>
instead of jsapi, according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
this will only change the load statement, see above snippet.
2) google.visualization.PieChart -- should be removed here --> chart.draw(figures, options);

I think you are missing with API Url Like,
$.ajax({
url: "api-url",
type: "GET",
success: function (data) {
});
Assumed the API Url in a variable so it should be-
$.ajax({
url: api-url,
type: "GET",
success: function (data) {
});

Related

How to Update DataTable with JSON data in Javascript?

I have a table TableElements and a Javascript valiable jsonData.
I want to reload TableElements' dataTable using the reload() method but without success.
The goal is to add a row to the table, inserting it into the database. This is the code I used so far
$.ajax({
url: 'AddRow.php',
type: 'POST',
data: {
CatProg: catProg,
CatUser: catUser,
CatPass: catPass,
CatInUso: catInUso,
CatDesc: catDesc,
CatUltimo: catUltimo,
CatDat: catDat
},
dataType: "text",
success: function(result){
// draw table again
var table = document.getElementById('TableElements');
table.remove();
var tableContainer = document.getElementById('tableContainer');
tableContainer.innerHTML = result;
jsonData = GetJsonFromTable(); // it works
$('#TableElements').DataTable({ ajax: 'data.json' }).reload(); //?? how to put 'jsonData' here?
},
error: function(){
alert("Request did not succeed. Reload and try again.");
}
});
}
This is what jsonData is holding:
[
{
"Aggiungi": "Modifica Elimina",
"CatProg": "1",
"CatUser": "user1",
"CatPass": "user1pass1",
"CatInUso": "Y",
"CatDesc": "desc",
"CatUltimo": "1",
"CatDat": "12-12-2001"
},
{
"Aggiungi": "Modifica Elimina",
"CatProg": "2",
"CatUser": "admin",
"CatPass": "admin",
"CatInUso": "N",
"CatDesc": "aaa",
"CatUltimo": "1",
"CatDat": "01-01-1999"
}
]

jQuery Datatables populate search data

On document.ready, my Datatable loads accordingly.
What I need to do is build a feature that reloads the Datatable if the user conducts a search.
So the Datatable loads like this:
$(document).ready(function()
{
$('#searchSubmit').on('click', function() // used for searching
{
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
var searchtli = $('#searchtli').val();
if(searchbooking == "" && searchquote == "" && searchtli == "")
{
$('.message').text('You did not enter any search criteria.');
return false; // making sure they enter something
}
else
{
$.post('api/searchAll.php', {searchbooking:searchbooking, searchquote:searchquote, searchtli:searchtli}, function(data)
{
// what do i do here???
// how do I get the return results to load
});
}
});
// if the user does not enter any search parameters, load everything
$('#example1').DataTable({
"ajax": {
"url": "api/displayQnams.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
// and so on
});
});
As you will see in the above code, when the document is ready, if the user does not conduct a search, I load all of the data from the process called 'displayQnams.php'.
But if the user conducts a search, the parameters are sent to another process called 'qnamsSearch.php'.
How do I reload the datatable with the search results from 'qnamsSearch.php'?
I tried to create a variable from inside the post:
var dataUrl = data;
And I tried to call that variable in the ajax call:
"ajax": {
"url": dataUrl,
"type": "POST",
"dataSrc": ''
}
But the Datatable will not display anything and there are no console errors.
How can I make this work?
You can try using this.
After user click search button, below is the flow:
Clear datatables - datatables clear()
Add new data to the table - datatables rows.add()
Adjust column size (optional) - datatables adjust.columns()
Redraw back datatable with new data - datatables draw()
$(document).ready(function(){
var datatable = $('#example1').DataTable({
"ajax": {
"url": "api/displayQnams.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]]
});
$('#searchSubmit').on('click', function(){
var searchbooking = $('#searchbooking').val();
var searchquote = $('#searchquote').val();
var searchtli = $('#searchtli').val();
if(searchbooking == "" && searchquote == "" && searchtli == ""){
$('.message').text('You did not enter any search criteria.');
return false; // making sure they enter something
} else {
$.post(
'api/searchAll.php',
{ searchbooking:searchbooking, searchquote:searchquote, searchtli:searchtli },
function(data) {
var newData = data;
datatable.clear().draw();
datatable.rows.add(newData); // Add new data
datatable.columns.adjust().draw(); // Redraw the DataTable
});
}
});
});

c3.js - How can I set the y lines value to the first value from url (json data)

How can I set the y lines value to the first value from URL? (JSON data)
var chartDisplay = c3.generate({
bindto: '.chart',
data: {
url: '/stats',
mimeType: 'json',
},
grid: {
y: {
lines: [ {
value: data1 <---- this is what I cant figure out
}
]
}
}
});
The json data looks like this:
{
"data1": 3000,
"data2": [
3000,
3300.0,
3410.0,
4520.0,
]
}
try adding this to your chart declaration,
onrendered: function () {
this.api.ygrids([
{value: this.data.targets[0].values[0].value, text:'data 1 value'},
]);
},
this.api is basically the same as the 'chart' variable, and this.data is a pointer to the loaded dataset. targets[0] will be the first series loaded (data1) and values[0].value will be the value of the first entry
http://jsfiddle.net/y7axwubf/1/

JSONp Datetime Javascript query fails on data.sparkfun iot

been trying to select data from data.sparkfun based on when its posted. I want to display weather data from the currenttime and a day back.
The stream is at: LINK
I am no coder, just hacking my way through here.
One json line is like this:
[{
"humidity": "37.8919",
"hectopascals": "1017.7725",
"rainin": "0.0000",
"tempc": "21.3162",
"winddir": "-1",
"windspeedkmh": "0.0000",
"windgustkmh_10m": "0.0000",
"timestamp": "2017-02-25T15:11:08.581Z"
}]
The code I use is at: https://www.hanscees.com/photon/charts-data-sparkfun.html
function drawChart2() {
var public_key = 'yA0EjKV3owhKNx1NlN3w';
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {
'gt': {
'timestamp': 'now - 2d'
}
},
dataType: 'jsonp',
}).done(function(results) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'TempC');
data.addColumn('number', 'Humidity');
$.each(results, function(i, row) {
data.addRow([
(new Date(row.timestamp)),
parseFloat(row.tempc),
parseFloat(row.humidity)
]);
}); // each row
// see https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart#dual-y-charts
var materialOptions = {
chart: {
title: 'TempC, Humidity outside'
},
width: 550,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {
axis: 'TempC'
},
1: {
axis: 'Humid'
}
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Pressure: {
label: 'TempC (Celsius)'
},
Humid: {
label: 'Humidity'
}
}
}
};
var materialChart = new google.charts.Line(ChartDivTemp);
materialChart.draw(data, materialOptions);
}); // results
} // jsondata
but the diagrams are either displaying all data in the json file (which makes it extremely slow), or when I use:
data: {page: 1},
it shows about 4 hours of data.
How can help to format the query correctly? This line:
data: {
'gt': {
'timestamp': 'now - 2d'
}
}
I did a post request thru Postman and it worked:
https://data.sparkfun.com/output/yA0EjKV3owhKNx1NlN3w.json?lt[timestamp]=now%20-2day
data: {
'lt': {
'timestamp': 'now - 2day'
}
}
So you code should work by adding 2day and changing gt to lt
This code does what I wanted:
// JSONP request
var jsonData = $.ajax({
url: 'https://data.sparkfun.com/output/' + public_key + '.json',
//data: {page: 1}, see http://phant.io/docs/output/http/
// https://forum.sparkfun.com/viewtopic.php?f=44&t=40621
data: {'gt': {'timestamp': 'now - 2day'}},
dataType: 'jsonp',
}).done(function (results) {

Highcharts not draw with JSON format

the problem is that the chart doesn't draw anything when the JSON response is obtained, the code is below:
var opciones = {
chart: {
type: 'bar',
renderTo: 'charterContainer'
},
series: []
};
var json;
$.get( "graficas.php?query="+data+"&rutas="+seleccion_rutas+"&residuos="+seleccion_residuos+"", function( tabla_conteo ) {
console.log(tabla_conteo);
json = jQuery.parseJSON(tabla_conteo);
var newSeriesData = {
name: json['1'].name,
data: json['1'].data
};
opciones.series.push(newSeriesData);
});
var chart = new Highcharts.Chart(opciones);
And the JSON response is:
{"1": { "name": "Jesus Emilio Ramirez ", "data":[ 111,127,308,262,0]},"2": { "name": "Bioterio ", "data":[ 0,391,0,359,284]}}
But if the data is introduced manually into the 'opciones' variable, the chart draws, so I believe that is a problem with the push or format.
Put chart creation inside your $.get() callback:
$.get( "graficas.php?query="+data+"&rutas="+seleccion_rutas+"&residuos="+seleccion_residuos+"", function( tabla_conteo ) {
console.log(tabla_conteo);
json = jQuery.parseJSON(tabla_conteo);
var newSeriesData = {
name: json['1'].name,
data: json['1'].data
};
opciones.series.push(newSeriesData);
var chart = new Highcharts.Chart(opciones);
});

Categories