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]);
Related
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
});
I am using the Kendo UI Grid. Basically, what I want to do is bind the grid on remote data which are sent on json format and be able to edit it.
The Grid receive the data and display it as I want. However, when I want to edit a cell, the request received in the php file is null, and the type sent is "create" while I would like it to be an "update".
Here is the code used:
-the javascript contains the grid declaration
$(document).ready(function() {
var dataSource = new kendo.data.DataSource({
batch: true,
transport: {
read: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=read"
},
update: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=update"
},
create: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=create"
},
destroy: {
dataType: "json",
type: "POST",
url: "testgrid.php?type=destroy"
}
},
schema: {
data: function(result) {
return result.Result || result.data;
},
model: {
id: "bbmindex",
fields: {
totalvente: {type: "number"}
}
},
total: function(result) {
return result.totalData || result.PageSize || result.length || 0;
}
}
});
var param = {
columns: [
{
field: "naturetravaux", title: "nature travaux"
},
{
field: "totalvente", title: "total vente"
}
],
selectable: 'multiplerows',
editable: true,
toolbar: ["create", "save", "cancel", "destroy"],
dataSource: dataSource
};
$("#grid").kendoGrid(param);
});
-the php script send the data to the dataSource
<?php
header('Content-Type: application/json');
$request = json_decode(file_get_contents('php://input'));
$type = $_GET['type'];
$result = null;
if ($type == 'create') {
some code
} else if ($type == 'read') {
some code which send the data
} else if ($type == 'update') {
some code
}
echo json_encode($result);
?>
any idea about what is wrong here?
Any help would be much appreciated,
thank you in Advance
Martin
If your server receives a create is because the idof the edited record is 0, null or undefined. Please check that you get from the server a field called bbmindex and is not 0
You expect the request to be posted as JSON however the Kendo DataSource doesn't do that by default. You need to use the parameterMap option and make it return JSON:
parameterMap: function(data, type) {
return kendo.stringify(data);
}
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);
}
}
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.
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.