My objective is to read data from a DB and plot it on a google combo chart but I need to improve the manner in which I want to pass my data from PHP to the JS controlling the combo chart
In PHP I've been able to connect to my DB, read from it and create a JSON data array from the successful read query.
I intend on calling my PHP code at the very start of my main PHP file i.e.
<?php include("../includes/db/dbread.php");?>
Essentially I need the successfully working PHP code shown below to be called by JS code which will be used to convert the JSON array into a suitable form to be used in the google combo chart
Here's the working PHP code i.e. dbread.php:
<?php
// 1.Create a database connection
define("DB_SERVER", "qwerty");
define("DB_USER", "qwerty");
define("DB_PASS", "qwerty");
define("DB_NAME", "qwerty");
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection occured
if (mysqli_connect_errno()) {
die("DB connection failed: ".mysqli_connect_error()."(".mysqli_connect_errno().")");
echo "DB connection FAILED !!!!";
} else {
echo "DB connection worked !!!!";
}
?>
<?php
//function dummy_fetch_sets($dbtable) {
$dbtable = "dummysets";
// Perform DB query
$query = "SELECT * FROM " . $dbtable;
$result = mysqli_query($conn, $query);
// Test for query error
if ($result) {
echo "DB connection worked !!!!";
// Create array and set as 2nd element of response array
$response["dummmysetsJSONArr"] = array();
// Copy values populate array to be used to generate JSON data
while($$dummysetsdetails = mysqli_fetch_assoc($result)) {
$dummysetsJSONArr = array();
$dummysetsJSONArr["entryID"] = $$dummysetsdetails["entryID"];
$dummysetsJSONArr["distance"] = $$dummysetsdetails["distance"];
$dummysetsJSONArr["calories"] = $$dummysetsdetails["calories"];
// Push one or more elements onto the end of array
array_push($response["dummmysetsJSONArr"], $dummysetsJSONArr);
}
// Set success value of response array
$response["success"] = 1;
//echo "Print out response in JSON format <br/><br/>";
//echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Could not SELECT ALL records";
//echo "<br /><br />Print out response in JSON format <br/><br/>";
//echo JSON response
echo json_encode($response);
//echo "<br /><br />";
die("DB " . $query . " query failed: " . mysqli_error($conn));
}
/*}
function db_close() {
if(isset($conn)) {
// Close DB connection
mysqli_close($conn);
}
}*/
?>
Here's the JS code from this post which I'm going to use with regards to fetching the JSON data from the above PHP script i.e.
// handles the click event for link 1, sends the query
function getSuccessOutput() {
myLogger("getSuccessOutput called");
getRequest(
'http://www.demoonlyurl.com/test/json.php', // demo-only URL
drawOutput,
drawError
);
return false;
}
// handles the click event for link 2, sends the query
function getFailOutput() {
getRequest(
'invalid url will fail', // demo-only URL
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
function myLogger(content) {
if (window.console && window.console.log) {
console.log("mylogger - " + content);
}
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
myLogger(req);
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) {
myLogger("false");
return false;
}
if (typeof success != 'function') {
myLogger("if (typeof success != 'function') {");
success = function () {};
}
if (typeof error!= 'function') {
myLogger("if (typeof error!= 'function') {");
error = function () {};
}
req.onreadystatechange = function(){
myLogger("req.onreadystatechange = function(){");
if(req .readyState == 4){
myLogger("if (typeof error!= 'function') {");
if(req.status === 200) {
myLogger("req.status === 200");
return success(req.responseText);
} else {
myLogger("req.status!= 200");
return error(req.status);
}
//return req.status === 200 ? success(req.responseText) : error(req.status)
}
}
req.open("GET", url, true);
req.send(null);
myLogger(req);
return req;
}
Below is my Google combo chart code from the tutorials which I intend on passing the JSON data array to.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Month', 'Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6'],
['Set 1', 165, 938, 522, 998, 450, 614.6],
['Set 2', 135, 1120, 599, 1268, 288, 682],
['Set 3', 157, 1167, 587, 807, 397, 623],
['Set 4', 139, 1110, 615, 968, 215, 609.4],
['Set 5', 136, 691, 629, 1026, 366, 569.6]
]);
var options = {
title : 'Chart title',
width: 1001,
height: 500,
vAxis: {
title: "VAxis title"
},
hAxis: {
title: "HAxis title"
},
seriesType: "bars",
series: {5: {type: "line"}}
};
var chart = new google.visualization.ComboChart(document.getElementById('number_format_chart'));
chart.draw(data, options);
}
Here's my qst:
I want to return the output of the PHP code without echoing its result so as to avoid printing but still have it available for my JS code to pick up.
How do I go about doing this?
LATEST EDIT:
As suggested by Alfonso Jiménez I've consolidated my JS code such that function drawVisualization() performs the interaction with the PHP code which returns the JSON data.
I've not yet used the JSON array to plot the bar charts. I intend on converting my JSON data to a 2 by 2 array so as to then be able to pass this data to
var data = google.visualization.arrayToDataTable([
As seen in my code below I'm unable to print my JSON array i.e. myLogger("myLogger - JSON ARRAY - " + jsonarry); for testing before using it to plot the charts
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var req = false;
var jsonarry;
try {
// most browsers
req = new XMLHttpRequest();
myLogger("myLogger - XMLHttpRequest() created");
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
myLogger("myLogger - req = new ActiveXObject(Msxml2.XMLHTTP);");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
myLogger("myLogger - req = new ActiveXObject(Microsoft.XMLHTTP);");
} catch (e){
}
}
}
if (!req) {
myLogger("req === false");
} else {
myLogger("req === true");
}
req.onreadystatechange = function(){
//myLogger("myLogger - req.onreadystatechange = function(){");
if(req.readyState == 4) {
myLogger("myLogger - req.readyState == 4");
if(req.status === 200) {
myLogger("myLogger - req.status === 200");
jsonarry = req.responseText;
myLogger("myLogger - JSON ARRAY - " + jsonarry);
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Month', 'Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6'],
['Set 1', 165, 938, 522, 998, 450, 614.6],
['Set 2', 135, 1120, 599, 1268, 288, 682],
['Set 3', 157, 1167, 587, 807, 397, 623],
['Set 4', 139, 1110, 615, 968, 215, 609.4],
['Set 5', 136, 691, 629, 1026, 366, 569.6]
]);
var options = {
title : 'Chart title',
width: 1001,
height: 500,
vAxis: {
title: "VAxis title"
},
hAxis: {
title: "HAxis title"
},
seriesType: "bars",
series: {5: {type: "line"}}
};
var chart = new google.visualization.ComboChart(document.getElementById('number_format_chart'));
chart.draw(data, options);
} else {
myLogger("myLogger - req.status == " + req.status);
}
//return req.status === 200 ? success(req.responseText) : error(req.status)
} else {
myLogger("myLogger - req.readyState === " + req.readyState);
}
}
req.open("GET", 'http://www.testingonetwo.com/dbread.php', true);
req.send(null);
}
function myLogger(content) {
if (window.console && window.console.log) {
console.log("myLogger - " + content);
}
}