How do I insert PHP variable inside jQuery/JavaScript bootstrap? - javascript

So this is my first attempt at using bootstrap i am trying to use "chart_filled_blue" in bootstrap but im having problems including my php results inside the jquery for bootstrap i would be thank full for any help or advice.
MY basic pdo select which grabs the views / date
$sth = $db->prepare("SELECT date, views FROM views_by_date");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
I will limit the select so it will only grab the last 6 or 7 rows
So now my chart_filled_blue.js is this
"use strict";
$(document).ready(function(){
// Sample Data
var d1 = [[1262304000000, 0], [1264982400000, 500], [1267401600000, 700], [1270080000000, 1300], [1272672000000, 2600], [1275350400000, 1300], [1277942400000, 1700], [1280620800000, 1300], [1283299200000, 1500], [1285891200000, 2000], [1288569600000, 1500], [1291161600000, 1200]];
var data1 = [
{ label: "Total clicks", data: d1, color: App.getLayoutColorCode('blue') }
];
$.plot("#chart_filled_blue", data1, $.extend(true, {}, Plugins.getFlotDefaults(), {
xaxis: {
min: (new Date(2009, 12, 1)).getTime(),
max: (new Date(2010, 11, 2)).getTime(),
mode: "time",
tickSize: [1, "month"],
monthNames: ["Jan", "FebBBBB", "Mar", "Apr", "May", "June", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
tickLength: 0
},
series: {
lines: {
fill: true,
lineWidth: 1.5
},
points: {
show: true,
radius: 2.5,
lineWidth: 1.1
},
grow: { active: true, growings:[ { stepMode: "maximum" } ] }
},
grid: {
hoverable: true,
clickable: true
},
tooltip: true,
tooltipOpts: {
content: '%s: %y'
}
}));
});
I would like to replace all the var d1 with the views from the db and then the monthNames to the date from the db
What would the best way be to do this ?

You can replace d1 with <?php echo $result['view'];?>

You either insert the variable at build-time, e.g. you turn your JS script into a .php file and have:
...
var d1 = <?php echo json_encode($results_from_db); ?>;
...
Or you use an AJAX call to fetch the results from the server.
var d1;
$.get('fetchdata.php", {}, function(data) { d1 = data; });
If the d1 data you're fetching will never change for the life of the page, then insert it at page-build time. it'll save you having to fire off ANOTHER http request back to the server to fetch the data.
If the data does change periodically, then you can combine the methods. Use the PHP-only method to insert the "first draft" of the data, then use ajax to fetch the updates.

populate your database results in the beginning of the php page
$sth = $db->prepare("SELECT date, views FROM views_by_date");
$sth->execute();
$result = $sth->fetchAll();
$result = json_encode($result);
in javascript
var d1 = JSON.parse(<?php echo $result; ?>);

Related

Highcharts update x-axis categories dynamically

i'm looking for help with updating the x-axis categories on a Highcharts chart with periodically received data.
The chart is defined in a file called forecastgraph.html. It is loaded to index.php, the webpage where I want it displayed, by means of <?php require("widget/forecastgraph.html"); ?>. The chart renders as expected.
Live data which is handled via a js script (called mqtt.js) that receives incoming mqtt data in json format and using jquery updates various parts of index.php in this way: $("#elementid").html(a.b.c);. I load mqtt.js in the head of index.php using <script src="./js/mqtt.js"></script> This again works flawlessly.
What I am struggling with is how to pass incoming data from mqtt.js to the chart to update it as new data comes in. Specifically, I am trying to update the xAxis categories and the corresponding value pairs. Periodically, mqtt.js receives a new weather forecast and so the xAxis categories need to be updated with the new time period that the forecast applies to and the data needs to be updated to reflect the new high and low temperatures for the respective forecast periods.
The code for the chart is posted below. Any help would be appreciated.
Baobab
<script type="text/javascript">
$(function () {
$('#forecastgraph').highcharts({
chart: {
type: 'columnrange',
backgroundColor: 'rgba(0,0,0,0)',
borderWidth: 0,
margin: [12, 6, 36, 20]
},
title: {
text: null,
},
exporting: {
enabled: false
},
credits: {
enabled: false
},
xAxis: {
categories: [1,2,3,4],
labels: {
y: 30,
style: {
color: 'white',
fontSize: '10px',
fontWeight: 'bold'
}
}
},
yAxis: {
title: {
enabled: false,
x: -14,
},
labels: {
align: 'left'
},
maxPadding: 0.5,
plotLines: [{
value: 10, //normmax
width: 2,
color: '#FF0000'
},{
value: 2, //normmin
width: 2,
color: '#009ACD'
}]
},
tooltip: {
enabled: false
},
plotOptions: {
columnrange: {
dataLabels: {
enabled: true,
style: {
textOutline: 'none'
},
crop: false,
overflow: 'none',
formatter: function () {
var color = this.y === this.point.high ? '#33C4FF' : 'red';
return '<span style="font-size: 12px; font-family:helvetica; font-weight:normal; text-shadow: none; color:' + color + '">' + this.y + '°</span>';
}
}
}
},
legend: {
enabled: false
},
series: [{
name: 'Temperatures',
data: [
[20, -3],
[5, -2],
[6, -2],
[8, -15]
],
color: '#b9deea',
borderColor: '#92cbde',
borderRadius: 4
}]
});
});
</script>
EDIT: Additional Information.
The incoming json data looks like this:
[{
"period": "Monday",
"condition": "Cloudy",
"high_temperature": "7",
"low_temperature": "-2"
"icon_code": "10",
"precip_probability": "20"
}, {
"period": "Tuesday",
"condition": "A mix of sun and cloud",
"high_temperature": "6",
"low_temperature": "-2"
"icon_code": "02",
"precip_probability": "20"
}, {
"period": "Wednesday",
"condition": "A mix of sun and cloud",
"high_temperature": "3",
"low_temperature": "-5"
"icon_code": "02",
"precip_probability": "20"
}, {
"period": "Thursday",
"condition": "A mix of sun and cloud",
"high_temperature": "1",
"low_temperature": "-10"
"icon_code": "02",
"precip_probability": "20"
}]
The function responsible for the incoming json formatted data in the mqtt.js script loaded to index.php handles the incoming data in this way (mqtt.js is started when index.php is loaded):
function onMessageArrived(message) {
console.log("onMessageArrived: " + message.payloadString);
//Env Canada forecast
if (message.destinationName == "myHome/ec/json_data_ec") {
var data = JSON.parse(message.payloadString);
$("#forecast_period_1").html(data[0].period); // update div forecast_period_1 in index.php for debugging purposes and show that data is coming in
forecast_period_1 = (data[0].period); // assign to global var
forecast_period_1_high = (data[0].high_temperature); // global var
forecast_period_1_low = (data[0].low_temperature); // global var
Updating various html elements throughout index.php with the incoming data works great and is stable. What I have attempted to do, but with no success, is to update the chart using the data placed in the global variables (declared as global at he beginning of the script) by the mqtt.js script. In the example above, forecast_period_1 needs to be used as the first of the four xAxis categories and forecast_period_1_high and forecast_period_1_low, to update the respective hi and lo values in the chart's data.
Is this an output that you want to achieve? In the below demo, I wrote a function that takes a high and low temperatures value and next is triggered on the button. The new data is attached to the chart via using the series.update feature.
Demo: https://jsfiddle.net/BlackLabel/he768cz3/
API: https://api.highcharts.com/class-reference/Highcharts.Series#update
I have found a solution for it. First, you have to store the chart in a variable then after you are able to update chart data. Like below
var chart = $('#forecastgraph').highcharts({ ...option })
Update xAxis or series data
// Update xAxis data label
chart.update({
xAxis: {
categories: [1,2,3,4]
}
});
// Update series data
chart.series[0].update({
data: [
[20, -3],
[5, -2],
[6, -2],
[8, -15]
]
});

how to get data from php to jquery

I have .php file and I have js file. I am trying to make bar chart. Now I have selected some data to my database. and now I don't know how can I get data from .php file to .js file.
I have this code:
//.js file
var data, options;
// replace this data with my selected data
data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
series: [
[19, 29, 28, 44, 39, 48, 54],
]
};
options = {
height: 300,
showArea: true,
showLine: true,
showPoint: true,
fullWidth: true,
axisX: {
showGrid: false
},
lineSmooth: false,
};
new Chartist.Line('#headline-chart', data, options);
/PHP FILE/
$chart6 = $controller->runQuery("SELECT DATE(pay_date) `DATE`, SUM(amount) daily_amount, DATE_FORMAT(pay_date,'%a') DAYNAME FROM tbl_paid WHERE DATE(pay_date) BETWEEN DATE(:today) - INTERVAL 1 WEEK AND DATE(:today) GROUP BY DATE(pay_date);");
$chart6->execute(array(":today"=>$today));
while($fetch = $chart6->fetch(PDO::FETCH_ASSOC))
{
$data ="{labels:".$fetch['DATE']."-".$fetch['DAYNAME']." series:".$fetch['daily_amount']."}";
}
You can read about ajax in javascript and make an ajax request that gets the json object from PHP then process that in your javascript:
Example (with some improvement to your PHP code)
PHP
$chart6 = $controller->runQuery("SELECT DATE(pay_date) `DATE`, SUM(amount) daily_amount, DATE_FORMAT(pay_date,'%a') DAYNAME FROM tbl_paid WHERE DATE(pay_date) BETWEEN DATE(:today) - INTERVAL 1 WEEK AND DATE(:today) GROUP BY DATE(pay_date);");
$chart6->execute(array(":today"=>$today));
$labels = array();
$series = array()
while($fetch = $stmt->fetch(PDO::FETCH_ASSOC)) {
$labels[] = $fetch['DAYNAME'];
$series0[] = $fetch['daily_amount'];
}
$series[] = $series0;
// add the labels and series to an array, then convert that to json
$data = array('labels' => $labels, 'series' => $series);
echo json_encode($data);
JS:
// Make an Ajax request, here I am using jQuery $.getJSON but you can use $.get or $.post if you need to have it as a post request, or even $.ajax
$.getJSON('https://example.com/database_fetch_page.php', function(data) {
new Chartist.Line('#headline-chart', data, options);
});

Chart.js; Chart is not showing time and imported data.

I am quite new to programming and expecially javascript.
To learn javascript I was thinking to create a chart using "ticker data" from coinmarketcap. To get the ticker data I created the following function:
function golemPrice() {
//Fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.coinmarketcap.com/v1/ticker/golem-network-tokens/?convert=EUR");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($curl);
curl_close($curl);
// decode to array
$data = json_decode($rawData);
//Access array[0] and select value price_eur
$gntPrice = $data[0]->price_eur;
// show data
return $gntPrice;
}
?>
To put the data into a chart, I was thinking to use chart.js. I created the following chart:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<script>
let priceFromFunction = ["<?php golemPrice();?>"];
let timeFormat = "MM/DD/YYYY HH:mm";
let myChart = document.getElementById('golemChart').getContext('2d');
let lineChart = new Chart(myChart, {
type: 'line',
data: {
datasets: [{
label: 'Golem chart',
borderColor: "rgba(80, 164, 245, 4)",
data: priceFromFunction
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
format: timeFormat,
// round: 'day'
tooltipFormat: 'll HH:mm'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}, ],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Price'
}
}]
},
}
});
</script>
Unfortunately my chart is not showing the date and no data from the function is added. I tried many different things but now I am out of ideas.
Hopefully you can help me.
You are missing echo the function value, try replace this:
let priceFromFunction = ["<?php golemPrice();?>"];
to
let priceFromFunction = ["<?php echo golemPrice() ?>"];

How to pass values dynamically in Script using php to produce graph

I am trying create a bar chart for the data in mysql using php. I use bootstrap template to create application. I have predefined barchart with static data. I wanna add the data from the database. I tried my best but could not find solution as I am beginner in Javascript. Please guide me to add data dynamically. The Script is below:
// Bar chart
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: '# of Votes',
backgroundColor: "#26B99A",
data: [10, 20, 30, 40, 20, 10, 40]
}, {
label: '# of Votes',
backgroundColor: "#03586A",
data: [41, 56, 25, 48, 72, 34, 12]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<div class="x_content">
<canvas id="mybarChart"></canvas>
</div>
If I understand the environment, you have php-produced webpages.
If so I would:
Create a .php file
Write some php code to connect to the database and to retrieve an array with the data to be charted
Copy your JS code, wrapped in <script> </script> tags and also wrap it in a JS Function which you'll call later in the page
Inside your JS code, after datasets, write a php loop as this:
// Bar chart
var ctx = document.getElementById("mybarChart");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
<?php
if (count($arrayOfData) > 0){
echo "label: '# of Votes',";
echo "backgroundColor: '#26B99A',";
echo "data: [";
$firstValue = true;
foreach ($arrayOfData as $dataValue) {
if ( ! $firstValue ) {
echo ", ".$dataValue;
} else {
$firstValue = false;
}
echo $dataValue;
}
echo "]";
} else {
//Decide what to do if you don't have data
}
?>
}]
}'
Write the rest of the HTML/PHP page.
Note that if you want more than 1 bar in your graph you have to also cycle through different data sets, not only through one as I showed above for simplicity.

Graphing Data with jQuery Flot from a MySQL database

I am trying to have a graph display registration data generated from the mysql database. The format for data seems to be coming out correctly but the data is not being plotted. Please note that I am using CodeIgniter.
PHP:
public function graph_registrations()
{
$send = array();
$i = 1;
while($i <= 30){
$startTime = mktime(0, 0, 0, date('m'), date('d')-$i, date('Y'));
$endTime = mktime(23, 59, 59, date('m'), date('d')-$i, date('Y'));
$data = $this->admin_model->total_users_date($startTime, $endTime);
$new = array(date("M j", $startTime), $data);
$send[] = $new;
$i++;
}
echo json_encode($send);
}
JS:
var jsonData = $.ajax({
url: default_url+"admin/graph_registrations",
dataType:"json",
async: false
}).responseText;
console.log(jsonData);
var graphData = [{
// Visits
data: jsonData,
color: '#71c73e',
points: { radius: 4, fillColor: '#71c73e' }
}
];
// Lines
$.plot($('#graph-lines'), graphData, {
series: {
points: {
show: true,
radius: 5
},
lines: {
show: true
},
shadowSize: 0
},
grid: {
color: '#646464',
borderColor: 'transparent',
borderWidth: 20,
hoverable: true
},
xaxis: {
tickColor: 'transparent',
tickDecimals: 2
},
yaxis: {
tickSize: 1000
}
});
Everything works if I manually hard code the data in, but not when I grab it via ajax.
This is what console.log(jsonData) produces:
[["Dec 5",0],["Dec 4",0],["Dec 3",0],["Dec 2",0],["Dec 1",0],["Nov 30",0],["Nov 29",0],["Nov 28",0],["Nov 27",0],["Nov 26",0],["Nov 25",0],["Nov 24",0],["Nov 23",0],["Nov 22",0],["Nov 21",0],["Nov 20",0],["Nov 19",0],["Nov 18",0],["Nov 17",0],["Nov 16",0],["Nov 15",0],["Nov 14",0],["Nov 13",0],["Nov 12",0],["Nov 11",0],["Nov 10",0],["Nov 9",1],["Nov 8",0],["Nov 7",0],["Nov 6",0]]
I tried doing it without the date and just a plain number, but it did not work.
Thank you
For me you are trying to plot the data before having them. I can see you are using "async:false" to wait for the data to be loaded by I'd rather used the default "true" option and placed the plotting function in "success" callback of $.ajax.

Categories

Resources