Echarts ajax data - php

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.

Related

Chartjs Data via json request not populating

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;

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
});

Highstock - How to add multiple series with JSON-Array

My target: I want to draw HighStock-chart with multiple series. Data is loaded by AJAX from data.php. The output of data.php is an JSON-Array
My problem: I don't know hot to grab the data from JSON Array
The output is e.g
[[timestamp,value1,value2],[timestamp,value1,value2]]
Series 1 should be -> timestamp and value1
Series 2 should be -> timestamp and value2
This is my code
// Draw the chart
$(function(){
/* The chart is drawn by getting the specific data from "data.php".
* The configuration settings are transmitted by GET-Method. The output is an JSON-Array. */
$.getJSON('data.php',
function(data) {
chart = new Highcharts.StockChart
({
chart: { renderTo: 'chartcontainer', type: 'line' },
title: { text: 'You see the data of the last hour!' },
xAxis: { type: 'datetime', title: { text: 'time' } },
yAxis: { title: { text: 'unit' } },
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
});
});
});
I think i have to change
series: [{ name: 'series1', data: data },{ name: 'series2', data: data }],
But I dont know in to what
Iterate through all items of the data array, and populate two separate arrays:
var series1 = [];
var series2 = [];
for (var i = 0; i < data.length; i++) {
series1.push([data[0], data[1]);
series1.push([data[0], data[2]);
}
You then have the timestamp-value pairs in each of the series arrays.
Doing this in php might be more efficient, especially if you can replace the current json creation.

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.

How to create a jqplot data array in PHP?

I am using ajax to connect to a PHP script and then retrieve the graph coordinates needed for the jqplot jQuery graphing library.
The problem is that I am having difficulties constructing a proper PHP array that can then be converted into a jQuery array that jqplot can read.
Here is the code that retrieves the array from the PHP file:
$.ajax({
type: 'POST',
dataType: "json",
url: "behind_curtains.php",
data: {
monthSelected: month_option_selected
},
success: function (data) {
var stored_data = data;
alert(stored_data);
}
});
return stored_data;
}
Here is the code that creates the jqplot
jQuery.jqplot('chartdiv-data', [], {
title: 'Plot With Options',
dataRenderer: stored_data,
axesDefaults: {
labelRenderer: jQuery.jqplot.CanvasAxisLabelRenderer
},
axes: {
xaxis: {
label: "Day",
},
yaxis: {
label: "data"
}
}
});
If you could please help me create the proper data array in the behind_curtains.php file it would be great!
Edit 1
the graphing coordinates array should be in the form of:
[[[1,2],[3,5],[5,13]]]
and basically I need to somehow write php code that can output an array that stores data in that form.
Thanks
Solution:
*behind_curtains.php*
I put together an array that simply generates a string in the form of [[1,2],[3,5],[5,13]]. I then stored the string in a variable and echoed that variable in the form of:
echo json_encode($stored_data);
On the user side of things here is how my code looked like:
<script type="text/javascript">
$("document").ready(function() {
$.ajax({
type: 'POST',
dataType:"json",
url: "behind_curtains.php",
data: {
monthSelected: month_option_selected},
success: function(data){
var stored_data = eval(data) ;
/* generate graph! */
$.jqplot('chartdiv-weight', [stored_data], {
title: month,
axesDefaults: {
labelRenderer: jQuery.jqplot.CanvasAxisLabelRenderer
},
axes: {
xaxis: {
label: "Day",
},
yaxis: {
label: "data"
}
}
});
}
});
}
}});</script>
I hope that helps, if no, whoever is interested please let me know.
You can return the stored_data but you need to have it declared before the AJAX call, like shown in the bottom most example, here. You must also use: async: false otherwise you cannot return your data in this fashion. For the same reason if you like you could use getJSON() instead.
As it goes to formatting your retrieved data a similar issue I answered here. You need to build your array accordingly to represent your data.
If you can show how exactly does your JSON look like then I could give you a more precise answer.

Categories