Chartjs Data via json request not populating - php

I'm using PHP and SQL to produce an array which counts data with the same values and how many of those value there are which outputs a json_encode to:
{"05":4,"09":4,"19":4}
Chart.js file: (trimmed down)
// Chart
var ctx = document.getElementById("monthAbuseChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1", "2", "3"],
datasets: [{
label: "Offences",
//data: [0, 7, 5] This works
data: offences // This doesn't
}],
}
}
});
// Grab the data for offences:
var offences = []
$.ajax({
method: "POST",
url: "sql/monthabuse.php",
dataType : 'json',
success: function (result) {
//offences = result;
var offences = result;
console.log(result);
},
});
The console.log outputs {19: 4, 05: 4, 09: 4}
However, if I put offences into the data section data: offences it doesn't work?

Assuming that you want to populate the response of AJAX Call in offences variable.
There are 2 issues with your current code:
Your code to create chart is running before the AJAX Call has run. In your code you are referencing offences variable but it is not yet populated.
You have defined offences as a global Variable, which is ok. But inside the AJAX Call you are again defining a new Local Variable offences by prefixing it with var. You need to use the below code which is commented in your question to populate the Global offences var.
offences = result
One way of fixing this would be to encompass your Chart Code in a New Function and inside the success callback of AJAX, call this New Function.
//Global Variable
var offences = [];
function createMonthAbuseChart() {
var ctx = document.getElementById("monthAbuseChart");
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["1", "2", "3"],
datasets: [{
label: "Offences",
//data: [0, 7, 5] This works
data: offences // This doesn't
}],
}
}
});
}
// Grab the data for offences:
$.ajax({
method: "POST",
url: "sql/monthabuse.php",
dataType : 'json',
success: function (result) {
offences = result;
console.log(result);
createMonthAbuseChart(); //Call the Chart Create Method Here.
},
});
You must make sure that data returned by AJAX Call has the same format as the data required for chart which is [0, 7, 5]. From your question it looks your AJAX Call is returning {19: 4, 05: 4, 09: 4}. You can use the following code to convert it into [4, 4, 4]
offences = Object.values(result);
Use the above line instead of following in your AJAX Callback
offences = result;

Related

Echarts ajax data

I tried to implement a chart with chart and ajax data type. When I would show result of a call in the xAxis not showing anything. This is a code of this chart
<div id="main" style="width:600px; height:400px;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
var dati = $.ajax({
url: '../../admin/root/chart.php', // provide correct url
type: 'POST',
dataType: 'JSON', // <-- since youre expecting JSON
success: function(chart_values) {
console.log(chart_values); // take a peek on the values (browser console)
}
});
// specify chart configuration item and data
option = {
legend: {},
tooltip: {},
dataset: {
// Provide data.
source: [
['product', 'Aperti', 'chiusi'],
['Cognome'],
]
}, // Declare X axis, which is a category axis, mapping
// to the first column by default.
xAxis : {
type: 'category',
data: dati
}, // Declare Y axis, which is a value axis.
yAxis: {}, // Declare several series, each of them mapped to a
// column of the dataset by default.
series: [
{type: 'bar'},
{type: 'bar'},
{type: 'bar'}
]
}
// use configuration item and data specified to show chart
myChart.setOption(option);
</script>
And this is what I call
$utente = mysqli_query($conne,"SELECT * FROM operatore") or die("Error:
".mysqli_error($conne));
while ($row=mysqli_fetch_array($utente)) {
$cognome=$row['cognome'];
$aperti=mysqli_query($conne,"SELECT * FROM rapportino WHERE
id_operatore='$row[matricola]'");
if ($aperti) {
$conta_ape=mysqli_num_rows($aperti);
}
$chiusi = mysqli_query($conne,"SELECT * FROM compila_rapportino WHERE
operatore_chius='$row[matricola]'");
if ($chiusi) {
$conta_chi=mysqli_num_rows($chiusi);
}
$myArray = array(
'cognome'=>$cognome,
'aperti' => $conta_ape,
'chiusi' => $conta_chi,
);
echo json_encode($myArray);
}
In this call data result can be repeat in different moment.
But from what I can see in your current post, you're dealing incorrectly with the Ajax call: you do the call, don't pass your data to the code that creates the chart. What you should do is to put this part of your code:
// specify chart configuration item and data
option = {
legend: {},
tooltip: {},
dataset: {
// Provide data.
source: [
['product', 'Aperti', 'chiusi'],
['Cognome'],
]
}, // Declare X axis, which is a category axis, mapping
// to the first column by default.
xAxis : {
type: 'category',
data: dati
}, // Declare Y axis, which is a value axis.
yAxis: {}, // Declare several series, each of them mapped to a
// column of the dataset by default.
series: [
{type: 'bar'},
{type: 'bar'},
{type: 'bar'}
]
}
// use configuration item and data specified to show chart
myChart.setOption(option);
inside the success callback and use the data that you get (chart_values):
var myChart = echarts.init(document.getElementById('main'));
var dati = $.ajax({
url: '../../admin/root/chart.php', // provide correct url
type: 'POST',
dataType: 'JSON',
success: function(chart_values) {
console.log(chart_values); // take a peek on the values (browser console)
//# put that code here and use chart_values!
}
});
This way, once you get the data, you'll be able to draw the chart.

Chart.js, PHP and JSON loop issue

I am trying to create a dashboard that will show some data from a database. Right now I am using a separate JSON encoded file named "data.php". I am using a jQuery Ajax request for this data to populate a Chart.js chart.
I have also been following an example similar to this
At the moment I am running into an issue seen here on my app.js file:
$(document).ready(function(){
$.ajax({
url: "http://{redacted ip}/swordtest/data.php",
method: "GET",
success: function(data) {
//var myData = $.parseJSON(data);
console.log(data);
var teamid = [];
var teamName = [];
var ticketCount = [];
for (var i in data) {
teamid.push("ID " + data[i].id);
teamName.push(data[i].name);
ticketCount.push(data[i].count);
}
console.log(data);
var chartData = {
lables: teamName,
datasets: [
{
label : 'Teams',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 0.75, 1)',
hoverborderColor: 'rgba(200, 200, 200, 0.75, 1)',
data: ticketCount
}
]
};
var ctx = $("#mycanvas");
var myDoughnutChart = new Chart(ctx, {
type: 'bar',
data: chartData
});
},
error: function(data) {
console.log(data);
}
});
});
What is happening though is that when I try to loop through the JSON object to separate the id's, names of the teams and amount of tickets, it will loop through the id continuously and give me this:
teamid = (1) ["ID undefined", "ID undefined"]
It will also add one and keep saying undefined. When I put breakpoints in the code it seems to only loop through the id as well. Any sort of help would be greatly appreciated. Thank you!
UPDATE
one thing to mention is that the data that I am getting from my data.php is a little different looking than the example I am working from (the link mentioned above). when I print the data it comes in this format:
data = "{"playerid":"1","score":"10"},{ "playerid":"2","score":"40"},{ "playerid":"3","score":"20"},{ "playerid":"4","score":"9"},{ "playerid":"5","score":"20"}"
Where in the example it looks like:
[{"playerid":"1","score":"10"},{ "playerid":"2","score":"40"},{ "playerid":"3","score":"20"},{ "playerid":"4","score":"9"},{ "playerid":"5","score":"20"}]
Different with brackets and without. I had a friend just try taking out the double quotes, replacing them with single quotes and wrapping the whole JSON in brackets. It seemed to start working then. I am guessing it has something to do with the way the JSON is getting formatted in my data.php.
Try to add the dataType property to the object literal that is the argument of the ajax() function. As you are getting a JSON from PHP, the property should have "json" as its value.
$.ajax({
url: "test.php",
method: "GET",
dataType: "json",
success: function(data) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("AJAX ERROR",textStatus,errorThrown,jqXHR);
}
});
I tested with this PHP file.
test.php
<?php
echo '[{"id":"1", "name":"John Doe", "count":"7"},{"id":"2", "name":"ABC", "count":"5"},{"id":"3", "name":"XYZ", "count":"29"}]';
?>

jQuery Select2 JSON data

My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

Highcharts with JSON

I'm trying to create a chart using data from my database calling json, but its not showing the results in the chart.
Here's my code so far:
$(document).ready(function() {
function requestData() {
$.ajax({
url: 'data.php',
datatype: 'json',
success: function(data) {
alert(data);
chart.series[0].setData(data[0]);
},
cache: false
});
}
var chart;
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events: {
load: requestData
}
},
xAxis: {
},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
And here's my data.php code
$query = "SELECT tiempo,Fp1Ref
FROM GraficaEEG limit 10";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$row['tiempo'] = (float) $row['tiempo'];
$rows[$i]=array($row['tiempo'],(float)$row['Fp1Ref']);
$i++;
}
echo json_encode($rows);
The data i receive is this:
[[0,3001],[0.005,4937.22],[0.01,4130.55],[0.015,4213.15],[0.02,4010.61],[0.025,3914.34],[0.03,3785.33],[0.035,3666.13],[0.04,3555.25],[0.045,3447.77]]
So i think is the proper way to pass data for the chart, so i don't quite get whats wrong, thank you in advance.
I think the problem is that when your requestData() function is fired the chart variable still isn't fully built and doesn't know it has the series property.
To fix this, instead of chart in your requestData() function, reference this (which means the chart object in that context).
I tried this out in jsfiddle here http://jsfiddle.net/elcabo/p2r6g/.
Also post the js code below.
$(function () {
$(document).ready(function() {
//Function bits
function requestData(event) {
var tiemposAlAzar = [[10,20],[20,50]];
//The 'this' will refer to the chart when fired
this.series[0].setData(tiemposAlAzar);
};
var chart;
//Chart bits
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
events:{
load: requestData
}
},
xAxis: {},
yAxis: {
title: {
text: 'Value'
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
});​
This url may help you to create dynamic highchart that need to pull data from database.
In json.php code you can put your sql query and replace static array to dynamic array
http://www.kliptu.com/free-script/dynamic-highchart-example-with-jquery-php-json
The example also shows how to manage multiple series with json.
And tooltips with all series data at mouse point.
You can modify example as per your script requirement.

Trying to pass multiple JSON data to Highcharts without success

I'm trying to create some Highstock charts (Highcharts) using sampled data but all I get when I run it its a blank page.
This is my php code:
<?php
header("Content-type: text/json");
$horas_muertas = array(array(1296518400000,4),array(1296604800000,2),array(1296691200000,3),array(1296777600000,3));
$horas_trabajadas = array(array(1296518400000,2),array(1296604800000,3),array(1296691200000,4),array(1296777600000,5));
$datos = array(json_encode($horas_muertas),json_encode($horas_trabajadas));
$datosj = json_encode($datos);
echo $datosj[0];
?>
As you can see I tried accesing the first location of the JSON, which returned this so I'm sure something's wrong there:
[
But when I use this code for the chart(I removed non-relevant code):
function requestData() {
$.ajax({
url: 'data.php',
datatype: 'json',
success: function(data) {
//alert(data);
chart.series[0].setData(data[0]);
chart.series[1].setData(data[1]);
},
cache: false
});
}
$(function() {
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
type: 'column',
events: {
load: requestData
}
},
series: [{
name: 'Horas Prendidas',
data: []},
{
name: 'Horas Trabajadas',
data: []}]
});
});​
All I get is a blank page,when I at least should get a chart without any data on it, any ideas on how to solve this? Help is much appreciated
Use chart.series[0].addPoint(data[0]); instead of chart.series[0].setData(data[0]);

Categories