What I'm doing:
Fetching data of tweets from MySQL using PHP; assigning the PHP output to a Javascript array; passing the JS array as a parameter to C3.js.
Problem:
The MySQL DB is constantly updated. So I need to update the C3 graph as well. My problem is that I'm mixing PHP and JS, so I'm not able to bundle them into the same function and call this function. How can I fetch the fresh data from the DB and update the graph?
Here's the code:
<?php
// Fetch data from DB
$sql = "SELECT created_at, COUNT(text) as tweetcounts from brexittweets group by created_at order by created_at desc limit 100";
$result = $conn->query($sql);
?>
<script>
var timeStamps = [];
var statusesCount = [];
timeStamps.push('timeStamps');
statusesCount.push('statuses');
<?php
if ($result->num_rows > 0) {
// assign PHP output to JS variables
while($row = $result->fetch_assoc()) { ?>
timeStamps.push('<?php echo $row['created_at'];?>');
statusesCount.push('<?php echo $row['tweetcounts'] ?>');
console.log(timeStamps);
<?php
}
} else {
echo "0 results";
}
?>
</script>
<?php echo '<div id ="chart2"></div>'?>
<script>
var chart = c3.generate({
bindto: '#chart2',
data: {
x: 'timeStamps',
xFormat: '%Y-%m-%d %H:%M:%S',
columns: [
timeStamps,
statusesCount
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format:'%H:%M:%S'
}
}
}
});
setTimeout(function () {
// Need to fetch fresh data here
}
Related
What i have trying to do draw a line chart based on date and Id mentioned in the date picker like this
Below is My Code which i am currently using to populate the line chart
HTML CODE (TO show the chart )
<html>
<head>
<title>Temperature chart</title>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<script type="text/javascript" src="js/jquery-3.4.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
data.php (using this file to get the data from mysql and printing it using json)
<?php
//setting header to json
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://localhost:8080/hurry/data.php', false);
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'canvasjs_db');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT `temp`, `formatedate` FROM `datapoints` WHERE `device_id` = '50' AND `formatedate` >= '2019-04-02 09:26:00' AND `formatedate` <= '2019-04-03 13:26:00'");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
app.js (using this file to populate the data in chart)
$(document).ready(function(){
$.ajax({
url: "http://localhost:8080/Notifications/NewNotification/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push(data[i].formatedate);
score.push(data[i].temp);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Temperature ',
hoverBackgroundColor: 'rgba(30, 0, 200)',
hoverBorderColor: 'rgba(200, 200, 197)',
data: score
}
]
};
var ctx = $("#mycanvas");
var lineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
im trying to populate a morris.js chart from a set of results. In my controller I create an array of the results and use json_encode to create a json array, here is the output in my view using print_r:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
How would I pass this to my morris.js chart to populate the chart using this data as label / value pairs? everything I try I get either a blank chart or an "undefined" variable or "NaN". Here is my controller:
function execute_search()
{
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Get results count and pass it as json:
$data = $this->search_model->count_res('$p_results_data');
$pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
foreach ($data as $item) {
if ($item['result'] === 'Positive') {
$pos++;
} elseif ($item['result'] === 'Negative') {
$neg++;
} elseif ($item['result'] === 'Pending') {
$pen++;
} elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
} else {
$misc++;
}
}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
$data = json_encode($res);
// Use the model to retrieve results:
$this->data['results'] = $this->search_model->get_results($search_term);
$this->data['chart'] = $data;
$this->data['totals'] = $this->search_model->total_res('$total_res');
// Pass the results to the view.
$this->data['subview'] = ('user/search_results');
$this->load->view('_layout_admin', $this->data);
}
and my morris.js:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
$results
],
});
Any help is greatly appreciated
Assuming that your morris.js is a normal javascript file, you cannot use php there by default: The server will not parse the .js file so the php source code will appear in your javascript.
You need to either:
Put the morris.js script contents in a php page in a javascript block so that the php gets parsed;
Make an ajax request from your morris.js script to get the data from the server in a separate request;
Set up your server to parse .js files as if they are / contain php.
The last one is just to illustrate what you would need, I would not recommend doing that.
In javascript, JSON.parse is your friend, assuming you have JSON that was created by PHP's json_encode function:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
JSON.parse( $results )
],
});
OR POSSIBLY
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( $results )
});
BUT THE WAY I DO IT
In the view:
<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />
In the JS (using jQuery):
var chartData = $('#chartData').val();
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( chartData )
});
After looking at the documentation for morris.js, I found that this is how you can do it the right way:
// Looking at the docs for morris.js:
// http://jsbin.com/ukaxod/144/embed?js,output
// This is your data, but it's all in one json object
var chartData = JSON.parse( $('#chartData').val() );
// We need to break up that object into parts of the donut
var donutParts = [];
$.each( chartData, function(k,v){
donutParts.push({
label: k,
value: v
});
});
// Now create the donut
Morris.Donut({
element: 'donutEg',
data: donutParts
});
I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.
Let say,
My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.
How can I store in Javascript after I converted them into json by
<?php
$sql = "SELECT public_holiday.holiday_date
FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
$json_array = json_encode($result_array);
echo $json_array;
?>
?
I have tried to store them into a javascript date array like
var holidays = [<?php //sample array for example
$loop_one = true;
foreach ($result_array as $date)
{
if ($loop_one)
{
echo "'new Date(\'$date\')'";
$loop_one=false;
}
else
{
echo ", 'new Date(\'$date\')'";
}
}
?>];
but all of these are invalid.
I need your help, much appreciated.
To get a javaScript date object array you need to change your script code only no need to change the PHP code.
You can use JSON.parse and forEach loop.
Try like this
<script>
var holidays = '<?php echo $json_array;?>';
holidays=JSON.parse(holidays);
var holidayArray=[];
holidays.forEach(function (key) {
holidayArray.push(new Date(key));
});
console.log(holidays);
console.log(holidayArray);
</script>
It will produce an out put as
I thing it will help you.
So in your sample, the $result_array variable will be a PHP array like:
$result_array = ['2017-06-25', '2017-06-26', '2017-06-27'];
You do not really need to convert this to JSON before passing it to your Javascript. Instead, you could print those string values directly into your Javascript to instantiate the date object, i.e.
<?php
$sql = "SELECT holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['holiday_date']; # Return the actual date value and not an array
}
?>
Javascript Part:
var holidays = [<?php
$firstLoop = true;
foreach ($result_array as $date_result) {
# Here you could format your $date_result variable as a specific datetime format if needed to make it compatible with Javascripts Date class.
if ($firstLoop) {
$firstLoop = false;
echo "new Date('$date_result')";
} else {
echo ", new Date('$date_result')";
}
}
?>];
In this example, I'm constructing a javascript array of new Date($phpDateTime) objects.
Your while loop should be like this and push the date into new array
<?php
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
//$result_array contains date like this $result_array = ['2017-06-26', '2017-06-27'];
?>
Javascript example
<script>
var holidays = [<?php $result_array = ['2017-06-26', '2017-06-27']; //sample array for example
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>
Update 1: Finally your code should be like this
<?php
$sql = "SELECT public_holiday.holiday_date FROM public_holiday";
$result = mysqli_query($conn, $sql);
$result_array = Array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row['public_holiday.holiday_dat'];
}
?>
<script>
var holidays = [<?php
$loop_one = true;
foreach ($result_array as $date) {
if ($loop_one) {
echo "'new Date(\'$date\')'";
$loop_one=false;
} else {
echo ", 'new Date(\'$date\')'";
}
}
?>];
console.log(holidays);
</script>
I'm trying to create a D3.js chart that requires data from a MySQL database. The chart is made using JavaScript, but I want to replace the values with the database value.
This works if I only try to input one value using PHP, but not if I add any more.
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
]; // This works
The above works, however, this doesn't:
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
{ name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data2"].""; } ?>}
]; // Adding another PHP value stops the entire chart from working (it works if I use a non-PHP second value).
I also attempted to just use one single while loop for all data, but that didn't work either.
<?php $connect = mysqli_connect("host", "user", "pass", "db");
$query = "SELECT data1, data2 FROM database WHERE x = y;
$result = mysqli_query($connect, $query); ?>
I know for sure that the data isn't the issue. I've tried the same thing on Google Charts and it worked without issue.
#create an array for the objects
$datasets=array();
#very unclear if your code fetches one or more rows,
#it seems one row with dataX fields
$row = mysqli_fetch_array($result);
#So we go over it
foreach($row as $field => $value) {
#create an object that becomes later {name:'abc',percent:'12'}
$obj = new stdClass();
$obj->name = $field;
$obj->percent=$value;
#collect it in the array,
#it becomes lates [{name:'abc',percent:'12'},{...},{...}]
$datasets[] = $obj;
}
#parse the data into the javascript part of the html content
?>
var datasets = <?php print json_encode($datasets);?>;
<?php
Hopefully, you can work with this.
If this is the real code you are using then the first bit of PHP consumes all of the resultset held in $result therefore there is nothing returned in the second bit of PHP
var dataset = [
{ name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data1"].""; } ?>},
// $result has already been fully consumed
{ name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
echo "".$row["data2"].""; } ?>}
];
Okay, I read a bunch of questions on StackOverflow but didn't seem to solve my problem.
I have a php file like this one:
<?php
require "config.php";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$conn->exec("SET NAMES UTF8");
$sql = "SELECT result.year, SUM(result.grade) AS year_total_points
FROM (
SELECT *
FROM students AS s
INNER JOIN points AS p
ON s.fn = p.student_fn
) result
GROUP BY result.year
ORDER BY year_total_points DESC";
$query = $conn->query($sql);
if($query->rowCount() > 0) {
$data = array (
"years" => [],
"years_total_points" => [],
);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data['years'][] = $row['year'];
$data['years_total_points'][] = $row['year_total_points'];
}
echo json_encode($data);
}
else {
echo mysql_error();
}
$conn = null;
?>
Long story short I make a query to the database and get a table with column year and column year_total_points. I want to store the data in an associative array so I can pass it to the js file. Because I later in the js file need an array of all years as strings and an array of all points also as strings, I decided to store them in an associative array. But I think that json_encode doesn't encode it as it should because executing the following code:
function success(data){
var barChartData = {
labels : data["years"],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : data["years_total_points"]
}
]
}
var ctx = document.getElementById("myChart").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
}
function error(){
alert('Error!');
}
window.onload = function(){
$.ajax({url: "http://localhost/year_comparison.php"}).done(success).error(error);
}
it says that data["years"] is undefined and I would expect it to be something like ["2011", "2012", "2013"]. Everything with the query is ok because when I added alert(data); I got a result {"years":["2011"],"years_total_points":["85.98"]}. But alert(data["years"]) says undefined. Any help to solve this issue would be greatly appreciated.