I want to dispay in a bar graph the days and the quantity.
I have following json output.(data.php) for each day the quantity.
[{"day":"2017-11-15","quantity":"72"},{"day":"2017-11-16","quantity":"157"},{"day":"2017-11-17","quantity":"130"},{"day":"2017-11-18","quantity":"91"},{"day":"2017-11-19","quantity":"96"}]
output.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
and thats the app.js
$(document).ready(function(){
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var day = [];
var quantity = [];
for(var i in data) {
day.push(data[i].day);
quantity.push(data[i].quantity);
}
var chartdata = {
labels: day,
datasets : [
{
label: 'DAYS',
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: quantity
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
but it's always empty. but why? Any idea? Also instead of the day theres only undefined on the bottom line.
Here is the main idea
data.forEach(function(packet) {
labelsData.push(packet.day);
datasetData.push(parseFloat(packet.quantity));
});
for example
var dataJSON = [{
"day": "2017-11-15",
"quantity": "72"
}, {
"day": "2017-11-16",
"quantity": "157"
}, {
"day": "2017-11-17",
"quantity": "130"
}, {
"day": "2017-11-18",
"quantity": "91"
}, {
"day": "2017-11-19",
"quantity": "96"
}];
var labelsData = [];
var datasetData = [];
dataJSON.forEach(function(packet) {
labelsData.push(packet.day);
datasetData.push(parseFloat(packet.quantity));
});
var chartdata = {
type: 'bar',
data: {
labels: labelsData,
datasets: [{
label: 'DAYS',
data: datasetData
}]
}
}
Working JSFiddle
https://jsfiddle.net/4v3nt7sL/1/
no plan why it's empty for me..
my database output is correct it think!
data.php
[{"day":"15","quantity":"72"},{"day":"16","quantity":"157"},{"day":"17","quantity":"130"},{"day":"18","quantity":"91"},{"day":"19","quantity":"96"},{"day":"20","quantity":"129"},{"day":"21","quantity":"140"},{"day":"22","quantity":"141"}]
index.html
<!DOCTYPE html>
<html>
<head>
<title>a simple chart</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
app.js
$.ajax({
type: 'POST',
url: 'data.php',
success: function (data) {
lineChartData = JSON.parse(data); //parse the data into JSON
var ctx = document.getElementById("mycanvas").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
Related
I'm trying to implement Fullcalendar timeline feature to show which meeting room is booked. I want to show who booked the room and what the meeting is about but currently I haven't been able to show who booked the room. In my database I have "name" columns as well additionally to "title". I want to know How I can show the name in front of the title with a space in between.
My code looks like this.
<head>
<meta charset='utf-8' />
<link href="{{ asset('/css/main.css') }}" rel="stylesheet">
<script src="{{ asset('/js/main.js') }}"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
<h1></h1>
<div id='calendar'></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
locale: 'en',
scrollTime: '00:00',
editable: true,
selectable: true,
aspectRatio: 1.8,
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'myCustomButton'
},
initialView: 'resourceTimelineThreeDays',
views: {
resourceTimelineThreeDays: {
type: 'resourceTimeline',
duration: {
days: 31
},
buttonText: '31 days'
}
},
resourceAreaHeaderContent: 'Conference Room',
resources: [{
id: 'a',
title: 'A'
},
{
id: 'b',
title: 'B',
},
{
id: 'c',
title: 'C',
},
{
id: 'd',
title: 'D',
},
],
dateClick: function(date, event, view) {
$('#start').val(date);
$('#end').val(date);
$('#dialog').dialog({
title: 'Add Event',
width: 600,
height: 600,
modal: true,
})
},
events: "{{route('allEvent')}}"
});
calendar.render();
});
</script>
</body>
</html>
view
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
To display both the name and title in the FullCalendar timeline view you should update the events property to map each event object and concatenate the name and title properties into a single string separated by a space. And here you go :
events: function(info, successCallback, failureCallback) {
$.ajax({
url: "{{route('allEvent')}}",
success: function(result) {
// Map the event objects to include both the name and title
var events = result.map(function(event) {
return {
id: event.id,
resourceId: event.resourceId,
title: event.name + ' ' + event.title, // Concatenate name and title
start: event.start,
end: event.end
};
});
successCallback(events);
},
error: function(error) {
failureCallback(error);
}
});
}
I extract data from my mysqli db into JSON file like this.:
<?php
session_start();
include_once("../config.php");
$Name13 = $_SESSION['RNaam'];
$conn = new mysqli($servername ,$username, $password, $db);
$sqli = "SELECT * FROM metingen where Id > '20000' and Lijn ='Lijn 2' and FlakeType1 ='FLK PE DSD329 0216 P2S2' AND KleurL BETWEEN '60'AND '80' ORDER BY Id asc";
$result2 = mysqli_query($conn, $sqli);
//$rows = array();
$rows['metingen'] = 'metingen';
$rows['Datum'] = 'Datum';
while($r1 = mysqli_fetch_array($result2)) {
$rows['data'][] = $r1['Datum'];
$rows['data'][] = $r1['KleurL'];
}
$result2 = array();
//array_push($result2,$data);
array_push($result2,$rows);
print json_encode($result2, JSON_NUMERIC_CHECK);
$conn->close();
?>```
The result of my JSON looks like this.:
[{"metingen":"metingen","Datum":"Datum","data":["17-1-2022",77.42,"17-1-2022",77.46,"17-1-2022",75.71,"17-1-2022",78.37,"18-1-2022",78.86,"18-1-2022",78.41,"18-1-2022",76.51,"18-1-2022",76.03,"18-1-2022",75.48,"18-1-2022",75.6,"18-1-2022",75.25,"18-1-2022",76.53,"18-1-2022",78.01,"18-1-2022",77.63,"18-1-2022",78.51,"18-1-2022",78.67,"19-1-2022",76.16,"19-1-2022",75.38,"19-1-2022",75.55,"19-1-2022",73.71,"19-1-2022",76.91,"19-1-2022",77.25,"19-1-2022",78,"19-1-2022",77.81,"19-1-2022",77.65,"22-1-2022",77.21,"22-1-2022",76.97,"22-1-2022",77.43,"22-1-2022",78.08,"22-1-2022",75.76,"22-1-2022",76.12,"23-1-2022",76.07,"23-1-2022",76.32,"23-1-2022",77.43,"23-1-2022",77.97,"23-1-2022",78.03,"23-1-2022",77.86,"23-1-2022",76.41,"23-1-2022",76.69,"23-1-2022",76.44,"23-1-2022",76.4,"24-1-2022",76.2,"24-1-2022",75.97,"24-1-2022",76.85,"24-1-2022",76.2,"24-1-2022",77.56,"1-2-2022",74.88.......```
The page with highcharts looks like this.:
<!DOCTYPE HTML>
<?php
session_start();
?>
<script>
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
</script>
<html>
<head>
<?php
echo '<!-- <meta http-Equiv="Cache-Control" Content="no-cache"> -->';
echo '<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">';
echo '<meta http-Equiv="Pragma" Content="no-cache">';
echo '<meta http-Equiv="Expires" Content="0">';
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Grafiek</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("datatest01112022.php", function(json) {
/*options.series[0].name = json[0]['Reg_sample'];
options.series[0].data = json[0]['KleurL'];*/
chart = new Highcharts.Chart({
chart: {
renderTo: 'container2',
type: 'line',
marginRight: 130,
marginBottom: 100
},
title: {
text: 'Gemeten L* waarde van Prep 2 bij Extrusie 2',
x: -20 //center
},
subtitle: {text: '',x: -20},
xAxis: { title: {
text: 'Datum'
}},
yAxis: {
title: {
text: 'KleurL'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
//return '<b>'+ this.series.name +'</b><br/>'+
return '<b>Meetwaarden</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {layout: 'vertical',align: 'right',verticalAlign: 'top',x: -10,y: 100,borderWidth: 0},
yAxis: {
plotLines: [{value: 70,color: 'red',dashStyle: 'longdashdot',width: 2,label: {text: 'Minimum'}},
{value: 80,color: 'red',dashStyle: 'longdashdot',width: 2,label: {text: 'Maximum'}},
{value: 75,color: 'green',dashStyle: 'shortdash',width: 2,label: {text: 'Richtlijn' },
}]
},
series: json,
});
});
});
});
</script>
</head>
<body>
<div id="container2" style="min-width: 400px; height: 400px; margin: 0 auto"> </div>
<!--<script src="highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>-->
</body>
</html>```
Why dosn't plot the highcharts the values and put the date/time into the x-axis in the line, but if i remove the date/time from my JSON file it works?
Can anybody solve my problem?
You need to adapt your data to the format required by Highcharts. In your case, it can be an array of arrays, each with two values.
data: [
[0, 1],
[1, 2],
[2, 8]
]
You should do that in your php script, but you can also use JS part:
const processedData = [];
for (let i = 0; i < json[0].data.length; i += 2) {
processedData.push([json[0].data[i], json[0].data[i + 1]]);
}
json[0].data = processedData;
Live demo: http://jsfiddle.net/BlackLabel/35cem86h/
API Reference: https://api.highcharts.com/highcharts/series.line.data
I'm need to transform the chart into an image and upload to server but just don't know what I'm doing wrong... It looks like there is a conflict in the ajax parsing the image data. Also tried to use base64 encode/decode but nothing seems to work
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="chartjs-wrapper" style="display: block; width: 700px; height: 450px;">
<canvas id="myChart"></canvas>
</div>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B'],
datasets: [{
label: '#',
data: [12, 19],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
}
});
</script>
<script>
$(window).load(function() {
// CANVAS TAG TO IMAGE
var canvas = document.getElementById('myChart');
var context = canvas.getContext('2d');
var imageObj = new Image();
context.drawImage(imageObj, 0, 0, 700, 450);
var pngUrl = canvas.toDataURL();
var myFormData = new FormData();
myFormData.append('image', pngUrl.files[0]);
$.ajax({
type: "POST",
dataType : 'json',
processData: false,
contentType: false,
url: "upload.php",
data: myFormData
}).done(function(response) {
//alert(response);
}).fail(function(jqXHR, textStatus ) {
alert("Request failed: " + textStatus);
})
});
</script>
</body>
</html>
Maybe there's a problem with the FormData?
Is there a better approach to do this?
I added new PHP code to process uploaded image. Also changed the way you are sending image from JS.
<?php
if(!empty($_POST['image']) || !empty($_FILES['image'])) {
$fname = time().".png";
move_uploaded_file($_FILES['image']['tmp_name'], $fname);
} else {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="chartjs-wrapper" style="display: block; width: 700px; height: 450px;">
<canvas id="myChart"></canvas>
</div>
<img src="" />
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B'],
datasets: [{
label: '#',
data: [12, 19],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
tooltips: {
enabled: false
},
animation: {
onComplete: function(e) {
takeSpanshot();
}
}
}
});
</script>
<script>
function takeSpanshot() {
var canvas = document.getElementById('myChart');
// CANVAS TAG TO IMAGE
var base64 = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
fetch(base64)
.then(res => {
return res.blob();
})
.then(blob => {
var formData = new FormData();
formData.append('image', blob);
$.ajax({
url: "test.php",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: formData
}).done(function(e){
alert('done!');
});
});
}
</script>
</body>
</html>
<?php
}
?>
basically you was passing base64 directly and you need to convert it into blob
I am using chart.js in php program to print chart using jquery but not able to display chart
I have also included bootstrap files in my original code
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css">
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div style="width: 400px;height:400px;">
<canvas id="myChart" width="400" height="400" style="color: red;"></canvas>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script>
$(document).ready(function(){
var data1 = {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [{
label: 'My First dataset',
backgroundColor: '#16a085',
data: [10, 5, 2, 20, 30, 45]
}]
};
var options1 = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
var ctx = $('#myChart');
var piechart = new Chart(ctx).Bar(data1,options1);
});
</script>
</body>
</html>
Not able to display graph using
var piechart = new Chart(ctx).Bar(data1,options1);
but i can display chart using
var piechart = new Chart(ctx,{
type:'bar',
data:data1 ,
options: options1,
});
But I want to display chart using 1st method
I'm trying to save a Google Maps Marker's coordinates to my database after the user placed the Marker. When I send the coordinates to the server, I always receive an empty $_POST array.
Where did I go wrong?
Here's my index.php:
<!DOCTYPE html>
<html>
<head>
<title>MyMap</title>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/main.css">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=AIzaSyCZseZXpWTYc2Z2aI4mJEtoLz8WUYQCITM"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var loc;
var map;
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(46.2428219,20.14682)
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
var lat = event.latLng.lat();
var lng = event.latLng.lng();
$.ajax({
type: "POST",
url: "index.php",
data: lat,
success: function (data) {
console.log(data);
}
});
});
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="result">
<?php
print_r($_POST);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo 'POSTed';
} else {
echo $_SERVER['REQUEST_METHOD'];
}
?>
</div>
<div id="map_canvas"></div>
</body>
</html>
Add a key to your data?
data: {'lat':lat}
Try something like this:
var lat_value = event.latLng.lat();
var lng_value = event.latLng.lng();
$.ajax({
type: "POST",
url: "index.php",
data: {lat:lat_value},
success: function (data) {
console.log(data);
}
});
In your index.php script use:
$lat=$_POST['lat'];