Rickshaw : data for multiple series not working - php
I'm trying to create some charts using Rickshaw, importing the data with ajax generated in php.
If I use static datas, the chart displays;
If I copy/paste the data generated in the php (from a console/log()), the chart displays;
If I try to put the datas into a variable, and use that var in the js, it just doesnt' work. :(
This is my console log of what I get from the .php :
(As I said, if I copy paste that block of code into the .js substituting the "dataOutEvo" var, the graph displays as it should. So, I don't think the data is the problem.
[
{
name: "ligne",
data: [{x:0,y:35},{x:1,y:34},{x:2,y:36},{x:3,y:35},{x:4,y:40},{x:5,y:35},{x:6,y:37},{x:7,y:40},{x:8,y:45},{x:9,y:46},{x:10,y:55},{x:11,y:63},{x:12,y:61},{x:13,y:45},{x:14,y:48},{x:15,y:49},{x:16,y:45},{x:17,y:44},{x:18,y:52},{x:19,y:43},{x:20,y:37},{x:21,y:36},{x:22,y:37},{x:23,y:34}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:10},{x:1,y:15},{x:2,y:13},{x:3,y:15},{x:4,y:14},{x:5,y:16},{x:6,y:17},{x:7,y:25},{x:8,y:23},{x:9,y:24},{x:10,y:25},{x:11,y:28},{x:12,y:27},{x:13,y:21},{x:14,y:23},{x:15,y:19},{x:16,y:18},{x:17,y:16},{x:18,y:15},{x:19,y:14},{x:20,y:15},{x:21,y:16},{x:22,y:15},{x:23,y:16}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:45},{x:1,y:49},{x:2,y:49},{x:3,y:50},{x:4,y:54},{x:5,y:51},{x:6,y:54},{x:7,y:65},{x:8,y:68},{x:9,y:70},{x:10,y:80},{x:11,y:91},{x:12,y:88},{x:13,y:66},{x:14,y:71},{x:15,y:68},{x:16,y:63},{x:17,y:60},{x:18,y:67},{x:19,y:57},{x:20,y:52},{x:21,y:52},{x:22,y:52},{x:23,y:50}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:10},{x:1,y:15},{x:2,y:12},{x:3,y:5},{x:4,y:9},{x:5,y:15},{x:6,y:45},{x:7,y:125},{x:8,y:345},{x:9,y:256},{x:10,y:312},{x:11,y:345},{x:12,y:299},{x:13,y:165},{x:14,y:354},{x:15,y:368},{x:16,y:254},{x:17,y:213},{x:18,y:312},{x:19,y:165},{x:20,y:54},{x:21,y:32},{x:22,y:10},{x:23,y:5}],
color: palette.color()
},
{
name: "ligne",
data: [{x:0,y:2},{x:1,y:3},{x:2,y:2},{x:3,y:1},{x:4,y:1},{x:5,y:2},{x:6,y:3},{x:7,y:15},{x:8,y:45},{x:9,y:27},{x:10,y:40},{x:11,y:42},{x:12,y:35},{x:13,y:18},{x:14,y:42},{x:15,y:40},{x:16,y:30},{x:17,y:25},{x:18,y:40},{x:19,y:20},{x:20,y:6},{x:21,y:4},{x:22,y:2},{x:23,y:1}],
color: palette.color()
}
]
And this is the js where something goes wrong :
$(document).ready(function(){
$.ajax({
url: 'dataOutEvo.php', //le fichier qui va nous fournir la réponse
success: function(data) {
var dataOutEvo = data;
console.log(dataOutEvo);
var palette = new Rickshaw.Color.Palette( { scheme: 'spectrum2001' } );
var graph = new Rickshaw.Graph({
element: document.querySelector("#chart"),
width: 960,
height: 260,
renderer: 'line',
series: dataOutEvo
});
graph.render();
}
});
});
Could anyone tell me what goes wrong ? Thank you :) Mathieu
I'm asking myself now if I shouldn't go another way, using this:
$fp = fopen('dataoutevo.json', 'w');
fwrite($fp, json_encode($js));
fclose($fp);
And this :
var palette = new Rickshaw.Color.Palette();
new Rickshaw.Graph.Ajax( {
element: document.getElementById("chart"),
width: 800,
height: 500,
renderer: 'line',
dataURL: 'dataoutevo.json',
onData: function(d) {
Rickshaw.Series.zeroFill(d);
return d;
},
onComplete: function(transport) {
var graph = transport.graph;
var detail = new Rickshaw.Graph.HoverDetail({ graph: graph });
}
} );
But it's is still not working … Does anyone can help me and tell me what I'm doing wrong ?
Using your first implementation should work fine. I think your problem is when you call:
success: function(data) {
The data variable returned from PHP is actually a string (You can check this using the Javascript function) -
console.log(typeof(data));
On your PHP code you should be returning an (Associative) Array and make sure you're using the json_encode() function -
echo json_encode($output);
And on your JS side cast your returned data using the JSON.parse method -
var json_data = JSON.parse(data);
Hope that helps!
In your first implementation, add a dataType to the ajax call.
This should work fine:
$(document).ready(function(){
$.ajax({
url: 'dataOutEvo.php', //le fichier qui va nous fournir la réponse
dataType: 'json',
success: function(data) {
var dataOutEvo = data;
console.log(dataOutEvo);
var palette = new Rickshaw.Color.Palette( { scheme: 'spectrum2001' } );
var graph = new Rickshaw.Graph({
element: document.querySelector("#chart"),
width: 960,
height: 260,
renderer: 'line',
series: dataOutEvo
});
graph.render();
}
});
});
Notice the dataType: 'json' in the $.ajax call.
According to the JQuery documentation, adding the json dataType,
Evaluates the response as JSON and returns a JavaScript object. The
JSON data is parsed in a strict manner; any malformed JSON is rejected
and a parse error is thrown
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 });
How to access php array inside POST method of AJAX to pass the array to another file?
i have a php file which have a array like the following. $selectShiftarray = array(); $shift=$_POST['selectShift']; if ($shift) { foreach ($shift as $value) { array_push($selectShiftarray,$value); } } i need to access the $selectShiftarray inside the AJAX to pass the value to another php file. $.ajax({ type: 'POST', url: '../c/sampleTest.php', //data: {data = <?php $POST['selectShift'] ?> },//"id=78&name=Allen", dataType: 'json', success: function (json) { //alert('successful'); $.plot($("#placeholder"), json, { series: { stackpercent: true, bars: { show: true, barWidth: 0.6, align: "center" } }, xaxis: { tickSize: 1 }, yaxis: { max: 100, tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) + '%' } } }); } }); i tried to pass the array values in the data feild of the AJAX to sampleTest.php to perform calculation. If i pass the array value directly between the two php files, i want to include the sampleTest.php inside the current php file. My requirement is, i should not include the sampleTest.php file inside any php file, hence i go for POST method of AJAX. But i can't able to pass array to the sampleTest.php file. Since i'm new to AJAX i can't solve this problem. can anyone help me to solve this problem.
Printing $selectShiftarray array into AJAX code to send it to ../c/sampleTest.php through AJAX: function sendArrayToPHP(phpFile, parameterName, jsArray) { $.ajax({ url: phpFile, async: false, // Depending on what you want type: "POST", data: { parameterName : JSON.serialize(jsArray) } }).done(function( data ) { // Sent! }); } var arrayExample = $.parseJSON("<?=$selectShiftarray?>"); // This way // You can modify here the array if you want using JavaScript sendArrayToPHP("../c/sampleTest.php", "arrayParameter", arrayExample); Receiving the array from ../c/sampleTest.php (decoding JSON): $selectShiftArray = json_decode($_POST['arrayParameter'], true);
Thanks to axelbrz and Bergi for their Guidance which helped me to solve this problem , This Works for me, Here is my AJAX code in Controller : <script type="text/javascript"> $(document).ready(function(){ var jsonobj = <?php echo json_encode($selectShiftarray); ?>; $.ajax({type:'POST',url:'../c/sampleTest.php', data : { shift : jsonobj } , dataType: 'json', success:function(json){ //alert('successful'); $.plot($("#placeholder"), json, { series: { stackpercent: true, bars: { show: true, barWidth: 0.6, align: "center" } }, xaxis: {tickSize : 1}, yaxis:{max:100, tickFormatter: function(v,axis){ return v.toFixed(axis.tickDecimals)+'%'}} }); } }); }); </script> <div id="placeholder" style="width:600px;height:300px; top: -401px; left: 500px;"> </div> My sampleTest.php code, which receives the array send by controller and processing it. $selectShiftarray = array(); $shift=$_POST['shift']; if ($shift) { foreach ($shift as $value) { array_push($selectShiftarray,$value); } }
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]);