Display data from MYSQL Database to Morris.js PHP AJAX - javascript

I want to display the data from my database into a chart Morris.js to be precise. I need to choose a branch from my dropdown, when i choose a branch the total sales of that branch should be transferred to the Morris.js Bar chart. I am having a problem with transferring the data to the Bar Chart. I am using AJAX, PHP and Morris.js.
PHP Code for dropdown:
<select class="form-control" id="t-yearly">
<option value="">Branch</option>
<?php
require_once "connect.php";
$sql = "SELECT id,branch FROM tblLocation";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['id']."'>".$row['branch']."</option>";
}
?>
</select>
AJAX Code for chart display:
//Total Yearly Sales
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
success: function(branch_data){
new Morris.Bar({
element: 't-yearly-sales',
data: branch_data,
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
console.log(branch_data);
}
});
});
PHP Code for fetch_yearly_sales.php:
<?php
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST["branch"]);
$ar = array();
if(!empty($data)){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales WHERE branch_id=".$data." GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$ar[] = array(
'year' => $row['year'],
'sales' => $row['sales']
);
}
echo json_encode($ar);
}
else if (empty($data)){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$ar[] = array(
'year' => $row['year'],
'sales' => $row['sales']
);
}
echo json_encode($ar);
}

You didn't specify what problem you were experiencing, but from the code it looks like you're passing a JSON string to Morris, while it actually requires a JSON object. So try changing: data: branch_data to data: JSON.parse(branch_data). I could be wrong though, it would help if you specified what exactly wasn't working.

I suppose you need to use the function setData() instead of creating a new chart always. This updates the chart with data given in parameters. You need to change to something like this:
var branch_data = [];
var my_chart = new Morris.Bar({
element: 't-yearly-sales',
data: branch_data,
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
dataType: "json",
success: function(branch_data){
my_chart.setData(branch_data);
}
});
});
By the way, I mentioned the dataType to JSON in the code above so that you would not need to parse the result from server.

Related

How to create a dynamic number of datasets based on DB values

My goal is to render a graph in PHP using CanvasJS but with multiple datasets dynamically generated based on the values in a DB. Generating this graph with only 1 dataset was working just fine, making it "dynamic" seems to be a challenge.
For 1 dataset I used the code below:
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
Where $dataPoint is send to the JS code
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
type: "line",
dataPoints: <?php echo json_encode($dataPoint, JSON_NUMERIC_CHECK); ?>
}
]
});
chart.render();
});
</script>
So far, so good, so, next step is to extend this to multiple datasets. In this case, for each user in the view "completedgames" we will create a new dataset $datapoint and each $datapoint will be added to the overal dataset $datapoints as shown below:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($dataPoints, $dataPoint);
$dataPoint = array();
}
Where $dataPoints is the value now send to the same JS code as shown in above. Unfortunately this is where it goes wrong. data array_push() function doesn't feel right but I have no idea what the alternative is.
So, I hope this is sufficient information, all information is welcome and thanks in advance!
You have a few different problems, first when appending the data I would do this:
$dataPoint[] = array("x"=> $i , "y"=> $score);
Also I would get rid of this as it seems to be clearing out $dataPoint and might actually be creating additional levels in the array.
array_push($dataPoints, $dataPoint);
$dataPoint = array();
This code creates a $charts variable which looks like the data array in your javascript chart definition, rather than making a representation of just the dataPoints array. That should allow you to have as many data sets as you want.
$charts = [];
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$dataPoint = [];
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
$i++;
}
array_push($charts, array(
"type" => "line",
"dataPoints" => $dataPoint
));
}
<script type="text/javascript">
$(function () {
var chart = new CanvasJS.Chart("chartContainer", {
data: <?php echo json_encode($charts, JSON_NUMERIC_CHECK); ?>
});
chart.render();
});
</script>
Using James' input I was able to make my Graph with multiple lines. Just needed to reset the counter and $dataPoint array: here is the working code:
while($rowUsers = $stmUsers->fetch(PDO::FETCH_ASSOC)){
$name = $rowUsers['username'];
$stm = $pdo->prepare('SELECT * FROM public."completedgames" WHERE username = :username');
$stm->bindParam(":username", $name, PDO::PARAM_INT);
$stm->execute();
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
$score = calculateScore($row['difficulty'],$row['length']);
array_push($dataPoint, array("x"=> $i , "y"=> $score));
json_encode($dataPoint, JSON_NUMERIC_CHECK);
$i++;
}
//array_push($dataPoints, $dataPoint);
// $dataPoint = array();
array_push($charts, array("type" => "line", "dataPoints" => $dataPoint));
$dataPoint = array();
$i = 0;
}
Thanks for all your inputs!

How to get JavaScript variable through PHP post request?

I am posting the PHP file (post.php) through jquery ajax. And I want to get the data from it in the form of a javascript variable. I successfully get the data in my console. But I don't know how can I use this variable. You can see my code below.
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data);
}
);
my post.php page looks like this
#include('../../_partials/_dbConnect.php');
$region = $_POST['region'];
$district = $_POST['district'];
$sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
$result = pg_query($db_connection, $sql);
while ($row = pg_fetch_row($result)) {
$cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
}
<script>
var cols = [<?php echo '"'.implode('","', $cols).'"' ?>];
</script>
And the console.log(data) output like this,
<script>
var cols = ["94","32","361","0","118","159","0","243","702","1775","8","0","2","0","150","135","381","2","0","0","0","0"];
</script>
Your help is highly appreciated.
In your post.php, you can simply echo the array and jQuery should automatically convert it to an array as the response
// post.php
<?php
#include('../../_partials/_dbConnect.php');
$region = $_POST['region'];
$district = $_POST['district'];
$sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
$result = pg_query($db_connection, $sql);
while ($row = pg_fetch_row($result)) {
$cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
}
echo json_encode($cols);
?>
// Somewhere in your js
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data[0]);
}
);
in javascript use JSON.parse()
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
data=JSON.parse(data);
}
);```
And here you go, u can play with it as you need
Happy learning!

How to retrieve Json Data and display on Chart.Js

Hello everyone I am trying to retrieve some data from data.php then allowing my app.js to display the data via Chartjs.
The data that I want to display is feedbackrowcount & complainrowcount
Which I already did a query to retrieve what I want from mysql.
Below is my data.php that does the query and the json data
<?php
//setting header to json
header('Content-Type: application/json');
$mysqli = mysqli_connect('localhost','root','','customercaremodule');
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query1 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Feedback'");
$Countsql1 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Feedback'";
//execute query
$result1 = $mysqli->query($query1);
$res1 = mysqli_query($mysqli,$Countsql1);
$value1 = mysqli_fetch_assoc($res1);
$feedbackrowcount = $value1['total'];
//loop through the returned data
$data1 = array();
foreach ($result1 as $row) {
$data1[] = $row;
}
//free memory associated with result
$result1->close();
//query to get data from the table
$query2 = sprintf("SELECT FC_Category FROM fbcomplain where FC_Category ='Complain'");
$Countsql2 = "SELECT count(FC_ID) AS total FROM fbcomplain WHERE FC_Category ='Complain'";
//execute query
$result2 = $mysqli->query($query2);
$res2 = mysqli_query($mysqli,$Countsql2);
$value2 = mysqli_fetch_assoc($res2);
$complainrowcount = $value2['total'];
//loop through the returned data
$data2 = array();
foreach ($result2 as $row) {
$data2[] = $row;
}
//free memory associated with result
$result2->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data1);
print json_encode($data2);
print json_encode($feedbackrowcount);
print json_encode($complainrowcount);
?>
This is app.js that display the chart. I believe the Data: is the key to not being able to display the chart on my webpage. Please help me to write the statement needed to retrieve data from data.php to app.js. Thank you so much!
$.getJSON('http://localhost/customercare/data.php', function(data) {
console.log(data);
});
var oilCanvas = document.getElementById("oilChart");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var feedbackvscomplainData = {
labels: [
"Feedback",
"Complain"
],
datasets: [
{
data:
backgroundColor: [
"#FF6384",
"#FF6300"
]
}]
};
var pieChart = new Chart(oilCanvas, {
type: 'pie',
data: feedbackvscomplainData
});

not all ajax code working online

I have this code:
$.ajax({
type: "POST",
url: 'gets/getQuery.php',
data: {'type': $("#type").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#type"), options = '';
select.empty();
options = "<option value=''></option>";
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
where:
<select id="type"></select>
I'm using this same code about 10 times with different select (different IDs and different getQuery.php file).
On localhost,everything is working fine,however,on online server,only 2 of the selects can read data from php file.
This is the php code of getQuery.php:
<?php
include("../db.php");
if (isset($_POST['type'])) {
$type = trim($_POST['type']);
$result = array();
$type = mysqli_real_escape_string($con,$type);
$res = mysqli_query($con,"SELECT * FROM Table order by Type");
while ($row = mysqli_fetch_array($res)) {
$result[] = array(
'id' => $row['ID'],
'name' => $row['Type']
);
}
echo json_encode($result);
}
?>
Anyone knows what might be the problem?
Thanks

want to add custome tool tip to my line chart (tool tip will have some html content like button and some text)

I am populating the chart by getting the datatable as the response from other page.
so am creating json object at other side and transfer to the requesting site and their i parse the object and create the datatable and populating the chart.
var jsonData = $.ajax({
type: "post",
url: "getHourDrillChart.php",
data: $("#my_form").serialize(),
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData); //alert(""+obj.toSource());
var dataHour = google.visualization.arrayToDataTable(obj);\
chart.setDataTable(dataHour);
chart.setOptions(options);
chart.draw();
other site where i creating the chart data :
$data[0] = array('Hour',$user);
$getTownLocalityInfo = mysql_query($SQLString);
# set heading
//$data[0] = array('hour','Count');
$i=1;
$dayArray = array();
while( $row = mysql_fetch_assoc($getTownLocalityInfo)){
$date = $row['date'];
$hour = $row['day_hours'];
$count = (int) $row['sumCount'];
$dayArray[] = $hour;
mysql_query("INSERT INTO trend_hour_chart_temp(hour,$user,userId) VALUES ('$hour',$count,'$staffId')");
$data[$i] = array($hour , $count);
$i++;
}
echo json_encode($data);
You need to add a tooltip column to your DataTable. Add the tooltip column to your column headers first:
$data[0] = array('Hour', $user, array('type' => 'string', 'role' => 'tooltip'));
Then, in the while loop, add the tooltip data to your rows:
$data[$i] = array($hour , $count, 'tooltip string');

Categories

Resources