Draw Google Chart Loading Php Array Using Ajax Inside Native Javascript Method - javascript

I'm trying to load php array inside native javascript method of gwt application using ajax and display google chart. But it does not give required output...below are my codes
Server side:
$data = array();
$data [] = array("Name", "Value");
$data [] = array("PHP", 78);
$data [] = array("JAVA", 10);
$data [] = array("HTML", 120);
$table = json_encode($data);
echo $table ;
?>
Client side:
<html>
<head>
<title>Graph</title>
<!-- Load jQuery -->
<script type="text/javascript" language="javascript" src="ajax/ajax.nocache.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {'packages' : ["corechart"] });
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Native javascript method
private native void generateGraph()
/*-{
$wnd.google.load("visualization", "1", {
packages : [ 'corechart' ],
callback : drawChart
});
function drawChart() {
var jsonData = $.ajax({
url: "http://localhost:8080/Ajax/get_json.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = new $wnd.google.visualization.arrayToDataTable(obj);
var options = {
title: 'Graph'
};
var chart = new $wnd.google.visualization.LineChart(
$wnd.document.getElementById('chart_div'));
chart.draw(data, options);
}
}-*/;
thanks for reply!!!

Related

Uncaught (in promise) Error: Data for arrayToDataTable is not an array in visualizing data using https://www.google.com/jsapi

I am trying to visualize data from a javascript file as shown below.
data = [ ['Year','China','India'],
['C1960',1.83286768126466,1.96098348563911],
['C1961',-1.01552778731319,1.99843774000741],
['C1962',0.820455548748518,2.03190545392019],
.
.
.
['C1963',2.45764740395145,2.0569116837358],
['C2017',0.559121331017265,1.06259739387194],
['C2018',0.455899678672578,1.03732336037888],
['C2019',0,0]
];
The html code I am using is as below.
<html>
<head>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable( data );
var options = {
title: 'World Bank Data Visualization',
chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1300px; height: 600px;"></div>
</body>
</html>
I am getting the error as
Uncaught (in promise) Error: Data for arrayToDataTable is not an array.
at Object.gvjs_ll [as arrayToDataTable] (jsapi_compiled_default_module.js:188)
at drawChart (data.htm:9)
Can anyone help me please? When I am loading another javascript file like this, it perfectly works. I don't know what is wrong with my code.
In your html, you have a variable named data. Due to this, the variable data from data.js is shadowed. More detail about Variable Shadowing here.
To make your code work, change that variable name to something else.
Something like:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataVis = google.visualization.arrayToDataTable( data );
var options = {
title: 'World Bank Data Visualization',
chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataVis, options);
}

Show google chart on button click

I have the following div on a page where I would like a google chart to load on a button click:
html:
<div class="row">
<div class="col-lg-12">
<div class="card mb-3">
<div class="card-header"><b>System Voltage</b></div>
<div class="card-body">
<div class="row">
<div class="col-md-12" id="line_chart" style="width:100%;height:360px;">
<!-- SHOW GOOGLE GRAPH HERE --> <button class="btn">Plot chart!</button>
</div>
</div>
</div>
</div>
</div>
</div>
Google Chart:
<script type="text/javascript">
$(document).ready(function() {
$(".btn").click(function() {
google.charts.load('current', {
packages: ['corechart'], callback: drawChart
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei);
$resultdata = json_decode($result, true);
?>
var jsonData = <?php echo $result; ?> //{"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'65%'},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
});
});
});
</script>
At the moment, the button appears, but nothing is happening on the click.
I am trying to follow this example.
EDIT:
I have updated the google charts to exclude the callback statement, and also added libraries I am using. The chart shows up perfectly well when not using the button, but I would like it to show only when the button is pressed.
<script type="text/javascript">
$(document).ready(function() {
$(".btn").click(function() {
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei);
$resultdata = json_decode($result, true);
?>
var jsonData = {"Battery Voltage, (A)":{"2017-11-11T00:00:00.000Z":12.3,"2017-11-11T00:01:00.000Z":12.35,"2017-11-11T00:02:00.000Z":12.6,"2017-11-11T00:03:00.000Z":12.7,"2017-11-11T00:04:00.000Z":12.8},"Battery Current, (A)":{"2017-11-11T00:00:00.000Z":1.3,"2017-11-11T00:01:00.000Z":1.4,"2017-11-11T00:02:00.000Z":1.5,"2017-11-11T00:03:00.000Z":1.6,"2017-11-11T00:04:00.000Z":1.7}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'65%'},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
});
});
});
</script>
Libraries:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
when using the promise returned from the load statement,
the callback is not needed...
change the load statement as follows...
google.charts.load('current', {
packages: ['corechart'],
}).then(function () {
also need to ensure the library is included...
<script src="https://www.gstatic.com/charts/loader.js"></script>
EDIT
note: the following library is old and should no longer be used, you can remove it.
<script src="https://www.google.com/jsapi"></script>
see the release notes for more info...
the load statement will wait for the document to load,
no need for --> $(document).ready
recommend loading google first, then wait for the button click...
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$(".btn").click(function() {
var jsonData = {"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'65%'},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input class="btn" type="button" value="Draw Chart" />
<div id="line_chart"></div>
Add <script type="text/javascript" src="https://www.google.com/jsapi"> to the head of your html page to load the library for the chart
Maybe you forgot to import all the necessary files. Make sure you are importing the jquery cdn (or download the file to your server)
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
and google chart cdn
<script src="https://www.google.com/jsapi"></script>
and check if you need an API key to use the plugin.

Browser indicates: Can't Find Variable: $?

I am very new to javascript (jquery/json) I have written this code to render a chart of CanvasJS with a php/json data fetching script along with it.
However the chart won't show, when I implement my code in to it. When I used Console.log() in web browser to find the ReferenceError it says: Can't find variable: $ ...Chart.html:11
I have tried many things and I have read many [duplicate] question/answers saying that I didn't load the Jquery Library and a bunch of other options. I have tried implementing this line:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
And I have tried many variables, but I don't think I understand what I can use more in these two codes I have..
Any point into the right direction would be great.
Chart.html
<!DOCTYPE HTML>
<html>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<head>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
In the above code, it concerns this part:
$(document).ready(function () {
and my php for the JSON data fetching: data.php
<?php
//header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","WebApplication");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM info");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['id'] , "y" => $row['acceleration']);
array_push($data_points, $point);
}
$json = json_encode($data_points, 32); //define('JSON_NUMERIC_CHECK',32); // Since PHP 5.3.3
$json = str_replace("\"", "", $json); //replace all the "" with nothing
echo $json;
}
mysqli_close($con);
?>
I know that the stack overflow community always require more info, but for god sake, I don't know anymore, and I really want to learn this.
EDIT-1:
This is what I have know, yet no result.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
EDIT-2:DEFAULT CODE, WHICH WORKS:
This is the default code that doesn't use my data.php code and uses randomized data points as data-source. It's from Canvasjs and it works fine.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:600px;">
</div>
</body>
</html>
It looks like jQuery is being loaded after canvasJS. If Canvasjs needs to use jQuery, it will need to have jQuery loaded first. Try switching those lines so jQuery is loaded on top, and it will probably fix your error.
EDIT: Actually, it seems that the CDN that hosts your jQuery doesn't use $ as the name of your main jQuery object. If you change $ to "jQuery" that error should be resolved. For example:
$(document).ready
would become:
jQuery(document).ready
same with $.getJson
It looks like Jquery isn't being loaded properly, and I'm thinking it's because of your unconventional practice of including the external scripts directly after the element. Try moving them down to just before your own script, inside the head.
Edit: the post was updated and apparently this didn't help.
SOLVED IT
First include this line:
than include this line: BELOW the code, not above it.
Than go to my data.php and comment (or delete) this line: //$json = str_replace("\"", "", $json); //replace all the "" with nothing
why u ask? Well because CanvasJS requires Strings and not separate characters/integrers.
So that the output will be:
[{"x":"1","y":"5"},{"x":"2","y":"5"},{"x":"3","y":"4"},{"x":"4","y":"1"},{"x":"5","y":"8"},{"x":"6","y":"9"},{"x":"7","y":"5"},{"x":"8","y":"6"},{"x":"9","y":"4"},{"x":"10","y":"7"},{"x":"14","y":"7"},{"x":"15","y":"7"}]
Instead of:
[{x:1,y:5},{x:2,y:5},{x:3,y:4},{x:4,y:1},{x:5,y:8},{x:6,y:9}...etc.

'null' is not an object with Google chart (issue with select menu, onchange event)

I'm using the following Script:
<header>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</header>
<body>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Header');
data.addColumn('number', '');
data.addColumn('number', '');
data.addRows([
['Monday',300,43],
['Tuesday',250,545],
['Wednesday',122,78],
['Thursday',348,92],
['Friday',23,61],
['Saturday',39,93]
]);
var options = {
title: '',
hAxis: {title: '', titleTextStyle: '#efede9'},
backgroundColor: '#efede9',
legend: 'none'
};
var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
chart.draw(data, options);
}
</script>
<div id="area_chart_google" class="area-chart"></div>
<body>
I cannot use the script inside Header because I'm using dynamic content.
I figure it out to work when I first load the page, and after refreshing it. My problem now is that I'm using a select menu with an onchange event, similar to this:
<select id="form_frame1" name="frame1" onchange="getChart(this);">
<option value="area_chart_google" >Area Chart</option>
<option value="area_chart_2" selected="selected">Stacked Chart</option>
</select>
My getChart function is:
function getChart(selection) {
if (selection.value == "area_chart_2") {
document.getElementById('area_chart_2').style.display = 'block';
document.getElementById('area_chart_google').style.display = 'none';
}
else {
document.getElementById('area_chart_2').style.display = 'none';
document.getElementById('area_chart_google').style.display = 'block';
}
}
So, once my area_chart_google is not displayed (display: none) and I select it, I get the error:
*Firebug* google-visualization-errors-all-1
*Chrome* Cannot read property 'length' of null
*Safari* 'null' is not an object
I guess is something with getElementById, so I tried using:
window.onload = function(){ javascript code here }
And also:
$(document).ready(function() {
javascript code here
});​
Nothing happen. I get no error but the Chart don't appear.
Any help will be highly appreciated.
This is working for me:
function getChart(selection) {
if (selection.value == "area_chart_2") {
document.getElementById('area_chart_2').style.display = 'block';
document.getElementById('area_chart_google').style.display = 'none';
}
else {
document.getElementById('area_chart_2').style.display = 'none';
document.getElementById('area_chart_google').style.display = 'block';
drawChart(); //call this function when using this Google Chart
}
}
You need to load the Google API first:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
You also should have proper <body> and <head> tags in your script.
Otherwise the code is fine. The below works fine for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Header');
data.addColumn('number', '');
data.addColumn('number', '');
data.addRows([
['Monday',300,43],
['Tuesday',250,545],
['Wednesday',122,78],
['Thursday',348,92],
['Friday',23,61],
['Saturday',39,93]
]);
var options = {
title: '',
hAxis: {title: '', titleTextStyle: '#efede9'},
backgroundColor: '#efede9',
legend: 'none'
};
var chart = new google.visualization.AreaChart(document.getElementById('area_chart_google'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="area_chart_google" class="area-chart"></div>
</body>
</html>
not sure, but try doing :
google.load("visualization", "1", {packages:["corechart"]});
//..your drawChart() function code here
$(document).ready(function() {
google.setOnLoadCallback(drawChart);
});
I hope you have already included following script in your header:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Google Chart with ajax

I can't see what i'm missing. I can't seem to get the Google chart api running with a little bit of ajax. What am I doing wrong?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataSet = $.ajax({
url: "phpdata.php",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable([
dataSet
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
my php data:
['year', 'fixedassets'],
['2009', 1],
['2010', 1.2],
['2011', 1.6]
I don't know if it would solve your issue, I was facing a similar issue while rendering partials called from ajax calls. The drawChart function was not being called which basically meant that the setOnLoadCallback was not firing as expected. To overcome that, I modified my calls as follows:
google.load("visualization", "1", {packages:["corechart"]});
//google.setOnLoadCallback(drawChart);
$(function() {
drawChart(); //works
});
function drawChart() {
}
So basically I left the google method , and made my own self calling function which gets called whenever the page renders or the div is updated.
The problem is likely with your ajax call:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataSet = [ ['year', 'fixedassets'],['2009', 1],['2010', 1.2],['2011', 1.6]];
var data = google.visualization.arrayToDataTable(dataSet);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
This works, so it's not a problem with any of the existing code. Your format for the ajax call is using a bunch of depreciated jQuery calls, and without access to your server I can't test it, but you could try something like:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get("phpdata.php", function(response_data) {
var data = google.visualization.arrayToDataTable([response_data]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
and see if that works.
I think that the problem you're having is that you have a string: "['year', 'fixedassets'], ['2009', 1], ['2010', 1.2], ['2011', 1.6]" and you want it evaluated as an array: [['year', 'fixedassets'],['2009', 1],['2010', 1.2],['2011', 1.6]]. The easy-but-insecure way to solve this is to use eval(). you'd say:
$.get("phpdata.php", function(response_data) {
var data = google.visualization.arrayToDataTable(eval('[' + response_data + ']');
This is not-great-but-working as long as you completely control the server, and you're not getting any user input that could be sent from your server.
The 'right' way to do this would be to send actual json from your server, instead of sending what you're sending, and then use JSON.parse(response_data).

Categories