ChartJS - Barchart with onclick links - javascript

I have created a MySQL database and I am running xampp locally.
Here is my data.php:
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'products');
//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 date, url, price FROM table1");
//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);
The output file generates the date, price and url
When I then take a look at my barchart.html, I am trying to introduce a onclick link to url when user clicks on each bar.
$(document).ready(function(){
$.ajax({
url: "http://192.168.64.2/fs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var date = [];
var price = [];
for(var i in data) {
date.push("" + data[i].date);
price.push(data[i].price);
}
var chartdata = {
labels: date,
datasets : [
{
label: 'price',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: price,
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
This is the bar chart which is generated;
When I hover over the bar chart, the date and price show up, however on click, I want to send user to url, as pulled from the table1 in data.php

Related

Ajax won't retrieve the data from my script

Hello so i try to retrieve data from a .php with Ajax to make a Doughnut chart with Chart.JS
Here is what i have (value 1, 2, 3, 4 in the legend order) :
This is my Chart.JS Script :
// Set new defawult font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';
$.ajax({
url:"./inc/pie_chart.inc.php",
method:"GET",
success:function(data) {
console.log(data);
var appelsnum =[1];
var mailsnum =[2];
var anomaliesnum =[3];
var decnum =[4];
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Appels", "Mails", "Anomalies", "DEC"],
datasets: [{
data: [appelsnum, mailsnum, anomaliesnum, decnum],
backgroundColor: ['#36b9cc', '#1cc88a', '#e74a3b', '#f6c23e'],
hoverBackgroundColor: ['#2c9faf', '#17a673', '#a3281c', '#dbac32'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},
options: {
maintainAspectRatio: false,
tooltips: {
backgroundColor: "rgb(255,255,255)",
bodyFontColor: "#858796",
borderColor: '#dddfeb',
borderWidth: 1,
xPadding: 15,
yPadding: 15,
displayColors: false,
caretPadding: 10,
},
legend: {
display: false
},
cutoutPercentage: 80,
},
});
},
});
And this is my "pie_chart.inc.php" file (the one who Ajax is retrieving) :
<?php
header('Content-Type:text/plain');
require_once('./loggedin.inc.php');
require_once('./db.inc.php');
require_once('./settings.inc.php');
$sql="SELECT SUM(appels_res) AS totalsumappelsmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$appelsnum = mysqli_fetch_assoc($result);
$appelsnum = $appelsnum['totalsumappelsmonth'];
$sql="SELECT SUM(mails_res) AS totalsummailsmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$mailsnum = mysqli_fetch_assoc($result);
$mailsnum = $mailsnum['totalsummailsmonth'];
$sql="SELECT SUM(anomalies_res) AS totalsumanomaliesmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$anomaliesnum = mysqli_fetch_assoc($result);
$anomaliesnum = $anomaliesnum['totalsumanomaliesmonth'];
$sql="SELECT SUM(dec_res) AS totalsumdecmonth FROM resultats ORDER BY id DESC LIMIT 14";
$result = mysqli_query($conn, $sql);
$decnum = mysqli_fetch_assoc($result);
$decnum = $decnum['totalsumdecmonth'];
$data=array();
$data[0]=$appelsnum;
$data[1]=$mailsnum;
$data[2]=$anomaliesnum;
$data[3]=$decnum;
$result->close();
$conn->close();
print json_encode($data);
?>
When i'm visiting this page, there is what it's returning to me :
Theses are the good values that must be on the Charts.
However, i'm getting 1, 2, 3, 4.
Do you know how to fix this?
Thanks for reading :) Greetings.
You are getting 1,2,3,4 because they are hardcoded. Try changing
var appelsnum =[1];
var mailsnum =[2];
var anomaliesnum =[3];
var decnum =[4];
to
var appelsnum =[data[0]];
var mailsnum =[data[1]];
var anomaliesnum =[data[2]];
var decnum =[data[3]];

Expression expected Error when using php variables in ChartJS functions

I am trying to input my Controller variable in ChartJS Javascript file to Dynamically create charts in ChartJS
Expression Expected at "<?"
Controller.php
public function index(Request $request)
{
#$result= DB::select("SELECT * FROM table WHERE user_id =?", [$user_id]);
$result_arr = json_decode(json_encode($result), true);
$label_array = array();
foreach($result_arr as $d)
{
$label_array[]=$d['label_element'];
}
$data_array = array();
foreach($result_arr as $d)
{
$data_array[]=$d['data_element'];
}
return view('home', ['labels'=>$label_array, 'data'=>$data_array]);
}
chart-pie-demo.js:
// Pie Chart Example
var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: <?php echo json_encode($labels); ?>, // Error Line
datasets: [{
data: <?php echo json_encode($data); ?>, // Error Line
backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'],
hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'],
hoverBorderColor: "rgba(234, 236, 244, 1)",
}],
},

Can't create separate charts using chart.js

I want to display separate charts. When the user selects more than 1 SensorData on the page it should display the data of the sensors separately. What I'm now getting is basically a so called "multi chart", which I do not want.
This is the code for drawing the chart based upon the data that gets returned from the Ajax POST call:
var visualisesensor = [];
$(document).ready(function () {
//When the button is clicked it should add the ID's from the Sensors I want to visualise in to an array.
$("#visualisebtn").click(function () {
$.each($("input[name='removecheckbox']:checked"), function () {
visualisesensor.push($(this).val());
});
//This is where I create multiple DIVs based upon howmany Sensors the user selected to display
for (var i = 0; i < visualisesensor.length; i++) {
$("#chart-container").append("<canvas id=" + visualisesensor[i] + "></canvas>");
}
//This is where I basically draw the charts based upon the amount of sensors the user selected
$.ajax({
url: "visualise.php",
method: "POST",
data: {visualisesensor: visualisesensor},
success: function (data) {
var Sensornaam = [];
var Temperatuur = [];
for (var i in data) {
Sensornaam.push("Sensor: " + data[i].Sensornaam);
Temperatuur.push(data[i].Temperatuur);
}
var chartdata = []
for (var k = 0; k < data.length; k++) {
chartdata = {
labels: Temperatuur,
datasets: [
{
label: 'Sensor Temperatuur',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: Temperatuur[k]
}
]
};
}
for (var j = 0; j < data.length; j++) {
var ctx = $("#" + data[j].SensorID);
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
});
console.log(chartdata[j]);
alert('Chart has been added!');
}
},
error: function (data) {
console.log(data);
}
});
});
});
This is the visualise.php code:
<?php
//setting header to json
header('Content-Type: application/json');
include ('../DATABASE/connection.php');
if(isset($_POST["visualisesensor"]))
{
$j = implode(',',$_POST["visualisesensor"]);
$query = sprintf("SELECT SensorID, Sensornaam, Temperatuur FROM sensoren WHERE SensorID in ($j)");
$result = $con->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$con->close();
//now print the data
print json_encode($data);
}
?>
What I'm now getting is a multichart. It display the data that's in the array successfully, but just in the same chart. I want the data of the sensors to be separately displayed. How would I go about this?
What's inside data:
Picture of database:
Picture of the output I get (and don't want):
The success function of the $.ajax call is very odd; I can't understand why the data variable is iterated 3 separate times. Since no test data was provided in the question I've reverse-engineered some, based on the code, and created a simplified answer that draws three separate charts:
// spoofed user input for testing.
var visualisesensor = ['1', '2'];
// spoofed ajax result data for test purposes.
var data = [{
SensorID: '1',
Sensornaam: 'tempsensor',
Temperatuur: '45'
}, {
SensorID: '2',
Sensornaam: 'meter',
Temperatuur: '83'
}];
for (var i = 0; i < visualisesensor.length; i++) {
$("#chart-container").append("<canvas id=" + visualisesensor[i] + "></canvas>");
}
for (var i = 0; i < data.length; i++) {
var ctx = $("#" + data[i].SensorID);
var chartdata = {
labels: [data[i].Sensornaam],
datasets: [{
label: 'Sensor Temperatuur',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: [data[i].Temperatuur]
}]
};
new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart-container"></div>

Reading MySQL data into highstocks

So this is the first time i have really worked with high charts i have some data reading into high charts from my MySQL database, but the next step is to try and set up a high stocks chart. Whenever i try and use the same method as i did with high charts the chart doesn't work? This is what i want to aim for - StockChartDemo
PHP Code:
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "(SELECT date AS time ,IFNULL(RH,'null')AS humidity
FROM test ORDER BY date DESC LIMIT 20) ORDER BY time ASC";
$result = $conn->query($sql);
if ($result->num_rows>0){
$count =0;
echo '[';
while($row=$result->fetch_assoc()){
echo '['.$row["time"].',' .$row["humidity"].']';
$count++;
if ($count<"20"){
echo ',';
}
}
echo ']';
}else{
echo "[[],[]]";
}
$conn->close();
?>
html & jQuery:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="highstock.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var options = {
chart: {
renderTo: 'tempcontainer',
alignTicks: false,
height:320,
},
rangeSelector: {
selected: 1
},
title: {
text: 'Relative humidity'
},
series: [{
type: 'column',
name: 'Humidity',
data: json,
dataGrouping: {
units: [[
'month', // unit name
[1] // allowed multiples
], [
'week',
[1, 2, 3, 4, 6]
]]
}
}]
}
$.getJSON("stockdata.php", function(json) { /*Get the array data in data.php using jquery getJSON function*/
options.series[0].data = json; /*assign the array variable to chart data object*/
chart = new Highcharts.stockChart(options); /*create a new chart*/
});
function refreshChart(){ /*function is called every set interval to refresh(recreate the chart) with the new data from data.php*/
setInterval(function(){
$.getJSON("stockdata.php", function(json) {
options.series[0].data = json;
chart = new Highcharts.stockChart(options);
});
},60000);
}
});
</script>
<div id="tempcontainer"></div>
Presuming your query is returning the correct data you want. (I'm not up for mocking it out to test your query)
You should switch out the following code, and all that in-between.
if ($result->num_rows>0){
//snip
}
To use json_encode() instead.
$series = [];
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$series[] = [
$row["time"],
$row["humidity"]
];
}
}
header('Content-Type: application/json');
exit(json_encode($series));

how to change customize label function?

Now I am currently using Jvector Map. Its working well. When I click the country name its shows country name for default. Now I want to customize the label and show label database value?
Script code:
<script>
jQuery.noConflict();
jQuery(function(){
var $ = jQuery;
$('#focus-single').click(function(){
$('#map1').vectorMap('set', 'focus', {region: 'AU', animate: true});
});
$('#focus-multiple').click(function(){
$('#map1').vectorMap('set', 'focus', {regions: ['AU', 'JP'], animate: true});
});
$('#focus-coords').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 7, lat: 35, lng: 33, animate: true});
});
$('#focus-init').click(function(){
$('#map1').vectorMap('set', 'focus', {scale: 1, x: 0.5, y: 0.5, animate: true});
});
$('#map1').vectorMap({
map: 'world_mill_en',
panOnDrag: true,
focusOn: {
x: 0.5,
y: 0.5,
scale: 1,
animate: true
},
series: {
regions: [{
scale: ['#688FA0'],
normalizeFunction: 'polynomial',
values: {
// "YE":0.3,
// "UA": 136.56,
// "QA":0.72,
"GB": 2258.57,
// "GA":4.6,
"US": 14624.18,
//"UG":4.3,
//"UY": 40.71,
// "UZ":0.72,
"VU": 0.72,
// "VE":5.77,
// "VN": 101.99,
// "ZW":8.4,
// "ZM":2.5,
}
}]
},
onRegionClick: function (event, code) {
var map = $('#map1').vectorMap('get', 'mapObject');
var name = map.getRegionName(code);
$(document ).ready(function() {
$.ajax({
type: "GET",
url: 'database.php',
data: {country: name},
dataType: "text",
success: function(data){
alert(data);
}
});
});
},
});
})
</script>
Its MY script code when i click country showing name country name default i want display from database . i have created database its connected via ajax code above code i had mentioned.
here attach my php code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$_country = $_GET['country'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT countryId,country,pdogcoregion,ccl,category FROM countrydetails WHERE country='".$_country."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "category: " . $row["category"];
}
}
else {
echo "No database";
}
$conn->close();
?>
I need to change the label showing country name default.
I want set database display label ?
You can customise tooltip using onRegionTipShow method. Just take a look at example available here.

Categories

Resources