JSON from php into JS file - javascript

I'm trying to draw DB tables using php PDO which i successfully made using the following code:
test.php
<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
I need to take the results into a chart JS code which his data array is in this code:
initCharts: function() {
if (Morris.EventEmitter) {
// Use Morris.Area instead of Morris.Line
dashboardMainChart = Morris.Area({
element: 'sales_statistics',
padding: 0,
behaveLikeLine: false,
gridEnabled: false,
gridLineColor: false,
axes: false,
fillOpacity: 1,
data:
[{
period: '2011',
sales: 1400,
profit: 400
}, {
period: '2011 Q2',
sales: 1100,
profit: 600
}, {
period: '2011 Q3',
sales: 1600,
profit: 500
}, {
period: '2011 Q4',
sales: 1200,
profit: 400
}, {
period: '2012 Q1',
sales: 1550,
profit: 5
}],
lineColors: ['#399a8c', '#92e9dc'],
xkey: 'period',
ykeys: ['sales', 'profit'],
labels: ['Sales', 'Profit'],
pointSize: 0,
lineWidth: 0,
hideHover: 'auto',
resize: true
});
}
},
How do i replace the data : [json] with the JSON from the PHP result?

In php file after closing tag you need write JS part, like it
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
Be careful with the semicolon. Just need to correct a little JS script, but I think you can do it.

You would need to echo out the content type, so that browser sees return data and accept as json.
echo ('Content-type: application/json');
$json = json_encode($results);
echo $json;
I usually open up the google console, or firefox's firebug to see the response tab on the network tab you've sent to. From there, you can see what data you are getting back from server to check if you are echoing right data or not.
Furthermore, you can print them in console log by pluggin
console.log(data);
Within your javascript to confirm whether you are getting data in right format.
You might as well look upon some db document to pull out data just what you need.
Instead of SELECT * FROM pdotable, SELECT period, sales, profit would do.
Hope this helps.

// test.php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
header('Content-type: application/json');
echo $json;
//js
...
if (Morris.EventEmitter) {
//if you use jQuery
$.get('/test.php', {}, function(result) { //or use $.getJSON
dashboardMainChart = Morris.Area({
...
data: result,
...
xmlhttp if you not use jQuery

you only need this json_encode function
this accept an array as parameter and return a string json that you can insert inside a js code simple use echo function
the js code must insert in php file and not in external js

Related

How to properly display data in chartjs from SQL?

I got started with chartJS, so I really need guidance of where to look and learn. I'm trying to display duplicated data from my SQL to chartJS.
Example:
Table name: Traffic Violations
Data I want to display: Violation types (Speeding, drifting, seatbelt, etc).
How it should be displayed: Y-axis as numbers, X-axis as violation names.
I read this: SQL count how many duplicated values of a derived table
Watched this: 1.3: Graphing with Chart.js - Working With Data & APIs in JavaScript
also watched this: How to Switch Chart to Daily, Weekly and Monthly Data in Chart js
And this: Count Total number of rows in database in php -Analytics in php
I learned few things from each, but still didn't satisfy my knowledge needs to achieve the goal I want.
I want to display the data in "Daily", "Monthly", "Yearly" format.
Sounds like that's a totally different topic, because I want the "daily" chart to reset every 24 hours, and monthly every month without deleting the data from DB. None of these videos above shows me that, nor I couldn't find what I'm looking for..
So, how to prepare my DB for chartJS?
best practice to fetch data and show it in the chart?
Here is what I have so far:
<?php
header('Content-Type: application/json');
require_once('./backend/config/connection.php');
$sqlQuery = "SELECT violationType, count(*) AS duplicates FROM traffic_violations GROUP BY violationType ORDER BY duplicates DESC";
$statement = $connection->prepare($sqlQuery);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
if ($row->num_rows > 0)
{
// output data of each row
while($row = $row->fetch_assoc())
{
echo $row["duplicates"]. "<br>";
}
}
else
{
}
echo json_encode($data);
?>
Chart:
const ctx = document.getElementById('chart-test').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Speeding', 'Drifting', 'Sealtbelt', 'Wrong Parking', 'Wrong Lane Drive', 'No License'],
datasets: [{
label: 'Traffic Violations',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ['rgba(255, 99, 132)'],
borderColor: ['rgba(255, 99, 132)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});

Using PHP and Javascript in a hybrid way, to traverse through a loop

I am trying to draw two graphs using chartjs. I want to make my life simplier by using a for loop to declare the variables required for the chart object.
The thing is I have created a 2d array, with each row storing data for current year, the next row storing data for the consecutive year and so on. I am trying to access the row of the variable using loop.
Here is my Chart obj
var canvas6= {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[1]);$i++){ -------->Note here
echo $dataAgeGrp[1][$i]; -------->And here
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx126 = document.getElementById('canvas6').getContext('2d');
window.myPie = new Chart(ctx126 , canvas6);
});
So, I tried something like this
for(var k=0;k<3;k++){
var q=26;
var canvas+q = {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[k]);$i++){
echo $dataAgeGrp[k][$i];
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx1+q = document.getElementById('canvas'+q).getContext('2d');
window.myPie = new Chart(ctx1+q , canvas+q);
});
q=q+1;
But I am getting this error
Use of undefined constant k - assumed 'k' (this will throw an Error in a future version of PHP)
How do I fix it?
If you can use PHP variables in your JavaScript code, the contrary is not possible. The only way to pass JavaScript variable to PHP code is by request (reload page with GET/POST parameters or AJAX request)

DataTable not accepting json from database

I want to set up a datatable on my website and I found a table I want to use here and I have been trying to convert it over to what I need. I have not had much success in this endeavor. My current situation is the table is not populating with rows from a database table and I am getting a json response error. I can open the inspector look at the php file that queries the database returns json data and I can see that I am returning data in the format
{"data":[
{"ssn":"100192686","dob":"1977-02-01","fn":"Latoyia","mi":"H","ln":"Herdon"},
{"ssn":"100263201","dob":"1962-06-15","fn":"Adena","mi":"M","ln":"Couch"}
]}
which according to a json validator is valid json but when I reload my page I get an error
"table id=example - Invalid JSON response".
So if the json data is in the correct format but is not being returned correctly what do I do? here is a gihub for the project. I have included the mysql database file I am working with as well as a text file that has XHR results in it. I feel like this line $('#example').DataTable( { javascript is where my issue is
<?php
include_once 'header.php';
?>
<script src = 'https://code.jquery.com/jquery-1.12.4.js'></script>
<script src = 'https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js'></script>
<script src = 'https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js'></script>
<script src = 'https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js'></script>
<script src = 'JS/dataTables.editor.min.js'></script>
<link rel = "stylesheet" href = "https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<link rel = "stylesheet" href = "https://cdn.datatables.net/select/1.2.5/css/select.dataTables.min.css">
<link rel = "stylesheet" href = "https://editor.datatables.net/extensions/Editor/css/editor.dataTables.min.css">
<section class="main-container">
<div class="main-wrapper">
<h2>Home</h2>
<?php
if (isset($_SESSION['u_id'])) {
$sql = "SELECT * FROM employee;";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
echo
"<table id='example' class='display' cellspacing='0' width='100%'>
<thead>
<tr>
<th></th>
<th>ssn</th>
<th>dob</th>
<th>first</th>
<th>MI</th>
<th>last</th>
</tr>
</thead>";
}
}
?>
</div>
</section>
<script>
console.log("In the script open");
var editor; // use a global for the submit and return data rendering in the examples
$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
ajax: "infograb.php",
table: "#example",
fields: [ {
label: "Social#:",
name: "ssn"},
{
label: "DOB:",
name: "dob"},
{label: "First Name:",
name: "fn"},
{
label: "Middle Initial:",
name: "mi"},
{
label: "Last Name:",
name: "ln"
}
]
} );
$('#example').on( 'click', 'tbody td', function (e) {
var index = $(this).index();
if ( index === 1 ) {
editor.bubble( this, ['fn', 'mi', 'ln'], {
title: 'Edit name:'
} );
}
else if ( index === 2 ) {
editor.bubble( this, {
buttons: false
} );
}
else if ( index === 3 ) {
editor.bubble( this );
}
} );
var testData = [{
"ssn": "98727748",
"dob": "2016-02-05",
"fn": "jake",
"mi": "a",
"ln": "butler"
}];
$('#example').DataTable( {
dom: "Bfrtip",
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
columns: [
{//sets the checkbox
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: "dob" },
{ data: "ssn" },
{ data: "fn" },
{ data: "mi" },
{ data: "ln" },
],
order: [ 1, 'asc' ],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
} );
} );
console.log("End script");
</script>
<?php
include_once 'footer.php';
?>
and here is the php file that queries the database and returns(allegedly) the json data
<?php
include_once 'dbconn.php';
$rows = array();
$sql = "SELECT * FROM employee";
$result = $conn->query($sql) or die("cannot write");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
echo "<pre>";
print json_encode(array('data'=>$rows));
echo "</pre>";
?>
I have been at this for about 24 hours now, and I feel like I have a bonehead mistake here I just can't figure it out. Any help would talk me down off the cliff at this point.
Datatables can be a pain and it's worthwhile to make sure you read the documents provided by them as much as you can.
I can see 2 issues running over your code without running tests. First one is infograb.php won't save any data sent to it because all it does is return data when it's loaded. Secondly you are using the initiation code of the datatable to try and send data (presumably for the inline editing as you don't seem to require any variables to be sent for the data requested). My first step would be taking it back a step:
ajax:{
url: 'infograb.php',
type: 'POST',
data: {
json: JSON.stringify({ "data": testData })
},
dataSrc: 'data'
},
Should go back to
ajax:{
url: 'infograb.php',
},
Remove the pre tags from infograb.php as well as they are unnecessary.
That should load the data into the table for you. You can then start working on the editing side.
Worthwhile Reading and Documentation:
Ajax sourced data
PHP libraries
DataTables Editor 1.7.3 - PHP 5.3+ libraries

jqPlot loading via AJAX

I don't think I'm understanding JSON completely, here is my code:
$.ajax({
type: "POST",
url: baseurl + "analytics/grab_points"
}).done(function(data) {
console.log(data);
var line1=$.parseJSON(data);
console.log(line1);
var plot2 = $.jqplot('chartdiv', line1, {
title: 'Customized Date Axis',
gridPadding: {right: 35},
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
tickOptions: {formatString: '%b %#d, %y'},
min: 'May 30, 2008',
tickInterval: '1 month'
}
},
series: [{lineWidth: 4, markerOptions: {style: 'square'}}]
});
});
jqPlot seems to expect data like so:
[['2008-06-28 8:00AM', 4], ['2008-6-30 8:00AM', 1], ['2008-8-30 8:00AM', 5.7]]
(that should the content in var line1)
My server side code (PHP):
$test=array(
"2008-06-28 8:00AM" =>4,
"2008-6-30 8:00AM" =>1,
"2008-8-30 8:00AM" =>5.7,
);
echo json_encode($test);
My console logs:
{"2008-06-28 8:00AM":4,"2008-6-30 8:00AM":1,"2008-8-30 8:00AM":5.7} analytics:103
Object {2008-06-28 8:00AM: 4, 2008-6-30 8:00AM: 1, 2008-8-30 8:00AM: 5.7} analytics:105
Uncaught Error: No data specified
Pretty sure I'm going barbarian on this JSON (growing pains), any idea would be great.
if you want to get the same structure that jqPlot wants you'll have to change your array in your php code...
jqPlot is expecting something like in your php array-structure:
$test = array(
array("2008-06-28 8:00AM",4),
array("2008-6-30 8:00AM",1)
);
check example 2 on http://php.net/manual/en/function.json-encode.php (the $c)
the {} you see is just because you output it as object rather than as array, but this should be the same as the [] (this is also explained on the php manual)
EDIT: also i don't think this line: var line1=$.parseJSON(data); is still needed because your data is already json.

JSON data not showing in highstock Candlestick chart using PHP & MYSQL

I'm trying to create a highstock's candlestick chart using php and mySQL.
this is my code so far, really appreciate if anyone can help me with this:
This my code for retrieving data from mySQL database and convert it to JSON format (datachart.php):
$conn = mysql_connect("localhost", "root", "") or die (mysql_error ());
$db = mysql_select_db ("b27sim") or die (mysql_error ());
$result=mysql_query ("SELECT date, open, high, low, close FROM mb27_daily") or die (mysql_error ());
$data = array();
$count = 0;
while ($row=mysql_fetch_array($result))
{
$newdate = strtotime($row['date']) * 1000;
$data[] = array( $newdate, (float)$row['open'], (float)$row['high'], (float)$row['low'], (float)$row['close']);
$count++;
}
echo json_encode($data);
This is the result from datachart.php:
[[1350252000000,369.72,371.02,368.09,370.22],[1349820000000,366.58,369.13,364.92,368.92],[1349733600000,367.38,369.93,366.82,368.64],[1349388000000,367.28,371.85,367.2,369.9],[1349301600000,362.75,366.24,362.22,365.61],[1349215200000,363.34,363.54,361.27,362.27],[1349128800000,360.79,362.73,360.33,361.77],[1349042400000,360.75,360.75,357.94,359.46],[1348783200000,360.62,362.69,359.84,362.5],[1348696800000,356.39,361.01,355.32,359.34],[1348524000000,358,360.39,356.34,359.7],[1348437600000,357.96,360.99,355.92,356.89],[1348178400000,359.27,360.53,356.93,360.53],[1348092000000,358.74,359.31,356.51,358.01],[1348005600000,357.97,361.82,357.24,359.86],[1347919200000,359.8,360.34,356.78,358.5],[1233010800000,119.28,122.42,119.28,121.91]]
And this is my javascript code inside index.htm:
$(function() {
$.getJSON('datachart.php', function(data) {
// create the chart
chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
},
rangeSelector : {
selected : 1
},
title : {
text : 'IB27 Price'
},
series : [{
type : 'candlestick',
name : '',
data : data,
tooltip: {
valueDecimals: 2
},
dataGrouping : {
units : [
['week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]]
]
}
}]
});
});
});
and this is my div calling the container:
<div id="container" style="height: 500px; min-width: 500px"></div>
and this is the result:
I got has not graph inside, but showing the timeline at the bottom, the date range on right top, etc.
Appreciate you guys help on this as I've been banging my head for the last 4 hours because of this... :)
Thanks,
Raz
Your data should be sorted by x (timestamps), ascending.

Categories