Issue with highchart data display when parsing JSON data - php

I am trying to dynamically fetch the data from a PhP module, load it as JSON data into javascript and use this data to generate a Pie chart using HighCharts. The Pie chart is generating properly when I am using some static data but not loading when I am parsing JSON data and feeding that as input to the Highchart series object. I am sure this is something to do with the formatting of data while inputting to Highcharts but I am not able to figure that out for sometime now :( So thought would just reach out to you guys . I have attached the code here and the sample json output generated by the php module for your reference.
Sample JSON input generated from PhP module : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]. Need to parse this JSON input and feed as input to my HighCharts series object to generate a pie-chart showing "html" and "css" as pie-slices.
Any guidance would be appreciated.
Thanks.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Top Skills Analytics</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="highcharts.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2" align="center"><u><b><font size="4">Top Skills Analysis</font></b></u>
</td>
</tr>
<tr>
<td>
<div id="container" style="height: 500px; width: 500px; margin-bottom: 1em;"></div>
</td>
</tr>
</table>
<script type="text/javascript">
// Creates the HighChart using the dynamically generated data from PhP module
function loadCharts() {
// Parses the JSON data and returns an array of an array
var result = [];
// json from php is like : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]
$.getJSON('test.php', function (json) {
$.each(json, function (i, entry) {
result.push(entry.skill, entry.count);
});
});
//result = [["html",158],["css",134]]; --> this works
var options1 = {
"series": [{
"name": "Jobs",
"type": "pie",
"sliced": true,
"data": result, // works when populated with static value like [["html",158],["css",134]]
"pointWidth": 15,
"color": "#C6D9E7",
"borderColor": "#8BB6D9",
"shadow": true,
}],
"title": {
"text": "Top Skills Analytics"
},
"legend": {
"layout": "vertical",
"style": {
"left": "auto",
"bottom": "auto",
"right": "auto",
"top": "auto"
}
},
"chart": {
"renderTo": "container"
},
"credits": {
"enabled": false
}
};
var chart1 = new Highcharts.Chart(options1);
}
// Load the charts when the webpage loads for the first time
$(document).ready(function () {
loadCharts();
});
</script>
</body>

It works with static data because the count is an int
["html",158]
And it doesn't work with dynamic data because it returns a string count
{"skill":"html","count":"158"}
Notice the double quotes around the second code line?
You need to either cast your string to an int in php or in javascript before passing it to highcharts
And another thing, if you run the code highcharts should complain with an error
Uncaught Highcharts error #14: www.highcharts.com/errors/14
If you visit the link it basically says the same thing about strings.
There is another thing wrong with the code
[["html",158],["css",134]]
As you can see here we have an array of arrays and when we run your code with string to int parsing we get
["html", 158, "css", 134]
Notice the problem? We have an array of four elements.
What you need to do is:
result.push([entry.skill, entry.count]);
Push an array of two elements to the result variable and don't forget that count must be an int

Try this,
result.push([entry.skill, parseInt(entry.count)]);

Related

Sending reporting mail with chart

the question I am asking is from a code-architecture point of view. I am preparing a report in php which is built with a string $message and then send via a php mail function.
For example the report is built in the php file like that(basically concatenates strings):
$message .= <<<HTML
</td>
</tr>
</tbody>
</table>
HTML;
Further, I would like to include a chart. However, trying the following example and sending it per mail I get no chart and an empty <div style="width:900px;min-height:500px"></div> ==$0 value.
$message.=<<<HTML
<tr valign="top" align="center">
<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333', ],
['Silver', 10.49, 'silver'],
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ]
]);
var options = {
title: "Density of Precious Metals, in g/cm^3",
bar: {groupWidth: '95%'},
legend: 'none',
};
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div.innerHTML);
});
chart.draw(data, options);
}
</script>
<div id='chart_div'></div>
</tr>
HTML;
My guess is that javascript is not accepted by f.ex. GMail. Hence, I am trying to create a png beforehand which is then included in the report.
My preferred way of doing this would be the google charts library, however, it has no support for php and is entirely based on JavaScript.
Hence, my questions are:
How can I use the google chart library in my code?
Any other suggestions if above does not work?
I appreciate if you could provide an example!
Thx in advance!
Email clients strip Javascript, SVG, and other formats, so you can't use a chart library directly in email.
Your options include:
Use getImageURI to generate a PNG of your chart and send it to your server to be emailed. This is probably the best solution if you know a client will load every chart before it needs to be emailed.
Use a tool like wkhtmltoimage to "headlessly" render a webpage that displays your charts and save it as an image.
Use a chart image rendering web service like QuickChart to generate the chart image (fyi: this is an open-source project that I started).
QuickChart in particular is built on Chart.js, so you'd have to create a Chart.js chart definition as a string:
$chartConfig = "{
type: 'bar',
data: {
labels: ['Copper', 'Silver', 'Gold', 'Platinum'],
datasets: [{
data: [8.94, 10.49, 19.30, 21.45],
backgroundColor: ['#b87333', 'silver', 'gold', '#e5e4e2'],
}]
},
options: {
title: {
display: true,
text: 'Density of Precious Metals, in g/cm^3',
},
legend: {
display: false
}
}
}";
I've used a static string to match your example, but you can include dynamic variables like in any other PHP string.
Then encode this string into a URL:
$chartUrl = 'https://quickchart.io/chart?c=' . urlencode($chartConfig);
This URL returns a chart that looks like this:
Finally, add the chart to your email body as an HTML image tag:
$message .= "<img src=\"$chartUrl\"/>";

json data parsing with jquery and HTML

i am trying to parse json data from remote URL using Jquery. My data is in below format:
[
{
"UserId": "5",
"Name": "Syed",
"Lat": "23.193458922305805",
"Long": "77.43331186580654",
"EmailId": "syedrizwan#ats.in",
"LocationUpdatedAt": ""
},
{
"UserId": "98",
"Name": "Michael Catholic",
"Lat": "23.221318",
"Long": "77.42625",
"EmailId": "michaelcatholic#gmail.com",
"LocationUpdatedAt": ""
}
]
i have checked the data in json lint and it says it is correct data format. when i try to run it on my HTML page , it returns a blank page. My HTML code is a below:
<html>
<head>
<title>Jquery Json</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results.Name);
});
});
</script>
</head>
<body>
</body>
</html>
I am trying to retrieve names from the json string
results is an array of items, so you have to consider which item you want.
Normally, you'd go over the array in a loop, in a fashion similar to that:
$.getJSON('http://localhost/fbJson/json.php', function(results){
for(var i = 0; i < results.length; i++) {
console.log(results[i].Name);
}
});
There is an array of objects, you can reach them directly by using the index
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results[0].Name);
});
If you wish to iterate over the array you can use $.each and pass the results into it
$.each(results, function(key, val) {
document.write(val.Name);
});
Your json format is correct.
Use this code to access name in first row array:
document.write(results[0].Name);

Transferring data from MySQL to javascript

I am a newbie to MySQL.
I want to transfer data from MySQL table to javascript.
I want to create a multidimensional array in javascript using the table in MySQL.
This multidimensional array is to be used in other functions for calculation.
Is there any way to do it using PHP or JSON?
Read records from your database table in PHP page and Create JSON And send it to Javascript. JSON can hold any level of hierarchical data.
A sample JSON may looks like this
[
{
"Customers": [
{ "Name": "Steve", "ID": "A12" },
{ "Name": "Mark", "ID": "A22" }
]
}
]
JsonLint is a useful tool when working with JSON data. It can validate JSON.
If you want to populate the javascript data on initial page load, you can do something like:
<?php
// get stuff from DB
$array_from_db = ... // some value determined via MySQL queries
?>
<script type="text/javascript">
var db_array = <?php echo json_encode($array_from_db); ?>
</script>
<?php
// more PHP stuff
This should work
<?php
var query=mysql_query("SELECT fields FROM table WHERE condition");
while($obj=mysql_fetch_array($query)){
arr[]=$obj
}
$array=json_encode($arr);
?>
<script type="text/javascript">
var db_array = <?php echo $array; ?>
</script>

jQuery Highcharts: change chart type using dropdown list

i'm trying to change the value of chart as following
<!doctype html>
<head>
<script>
var chart1; // globally available
$(document).ready(function() {
var chart = 'pie'
$("select").change(function(){
chart = $('#chart').val();
alert(chart);
});
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: chart
},
yAxis: {
title: {
text: 'Temprature'
}
},
series: [{
name: 'mach_1',
data: [<?php
foreach($chart as $`row) {
echo $row['temp'].",";
}
?>]
}]
});
});
</script>
</head>
<body>
<div id="form">
<label>Select a chart : </label>
<select id="chart">
<option>pie</option>
<option>column</option>
</select>
</div>
<div id="container"></div>
</body>
</html>
i know this will change the value of chart on select, but it doesn't change the chart itself. Any ideas?
Your original question was very difficult to read and interpret; some of stackoverflow's code editor tags were intertwined with the code you attempted to post. In the future, it may help to put an example of your code on jsfiddle.
If I'm understanding the question correctly, you are looking to change the type of chart displayed. Show a pie chart of the data; now show a bar graph of the data; now show a line chart, etc.
When you have a Highcharts question, it's a good bet someone else has asked that question before on the Highcharts forum. In your case, I think this is true: "Change chart type dynamically?" - http://highslide.com/forum/viewtopic.php?f=9&t=5501&p=26274&hilit=switch+chart+types#p26274
In the Highcharts forum question linked above, Highcharts author Torstein Honsi answers the question and includes a fiddle you may find to be a useful starting point, as he's changing the chart type in it. http://jsfiddle.net/tccpT/ Later on, a Highcharts support team member includes a fiddle where we see another example of changing the chart type. http://jsfiddle.net/2hLr5/
When a pie chart involves more than two pieces of data, it is generally advisable to not use a pie chart as a means of visualizing data. The more values a pie chart has, the more difficult it becomes to perceive the relationships between those pieces of data.

Displaying values from a database (using mySQL) on a Flot graph

I'm trying to read in values from a db using php (mySQL) then have them show on a graph in flot. I know the values are read in correctly and I'm not getting any errors but the graph won't show.
Little help?
Thanks in advance.
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$graphdata[] = array( (int)$row[0], (int)$row[1] );
}
?>
/////
<div id="placeholder" style="width:600px;height:300px"></div>
<script language="javascript" type="text/javascript">
var dataset1 = <?php echo json_encode($graphdata);?>;
var data = [
{
label: "Random Values",
data: dataset1
}
];
var plotarea = $("#placeholder");
$.plot( plotarea , data);
</script>
The contents of your pastebin show that the JSON string you're outputting is invalid JSON.
var data = [{ label: "Random Values",data: dataset1}];
will validate if it's changed to:
var data = [{"label": "Random Values","data": "dataset1"}]
That's just an example, but I suspect that Flot is looking for a slightly different format, so you'll have to verify exactly what they're looking for against their documentation. I'm going through the same exercise right now with FusionCharts, so I'm feeling your pain. jsonlint.com is your friend on this one, output your JSON and verify it frequently. I'd also recommend that to initially get it working, start with just a string of JSON (even one that you copy from their examples) that you put right in your code. Get the chart working first, then work on getting your PHP to duplicate the example JSON string separately.
Try delaying creating the graph until the DOM is loaded:
jQuery(document).ready(function ($){
var plotarea = $("#placeholder");
$.plot( plotarea , data);
});

Categories