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.
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
});
Please help me to solve my problem.
$("#kategori_laporan").change(function() {
$("#loaderIcon").show();
$("#imgLoader").show();
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "html",
url: "_views/getAjaxSubKategori.php",
data: "id="+id,
success: function(data) {
$(".select-skategori").select2({
ajax: {
url: "_views/getAjaxSubKategori.php",
dataType: 'json',
data: function(term, page) {
search = term.toUpperCase();
},
results: function(datas, page) {
return {
results: data
};
}
},
formatResult: function(option) {
return "<div>" +option._sub_kategori_laporan+ "</div>";
},
formatSelection: function(option) {
return option._sub_kategori_laporan;
}
});
}
});
});
Data not showing to subcategory select. Thanks before.!
Screenshot >> http://i.imgur.com/FlCeGpo.jpg
Why are you firing an ajax request before you initialize the select2 box?
I ask this, because your select2 box is requesting the search results via ajax as well. But maybe there is a reason. Please explain.
Then I can see in your screenshot, that your data returned from the json ajax request has not defined values id and text. If you are using other values ('_sub_kategori_id' and '_sub_kategori_laporan') in your json result, you have to tell the select2 box, what is your id and text field. I think you can do this with the processResults method as described here:
How to load JSON data to use it with select2 plugin
This should be a fairly simple call but I just can't seem to make it work. Basically, I'm trying to pass a set of search parameters to a PHP script but $_POST is coming up empty. The call (via jQuery)...
self.search = function () {
var data = {
'year': 2013,
'month': 10,
'day': 1
};
$.ajax({
dataType: 'json',
type: 'POST',
url: 'repositories/blogposts.php',
data: { 'search': data },
success: function(results) {
// populate knockout vm with results...
}
});
};
The PHP code waiting to do something with the incoming json object...
if (isset($_POST['search'])) {
echo find_blogposts(json_decode($_POST['search']));
}
I've tried this many ways but no matter what, print_r($_POST) gives me an empty array. What's missing?
PHP is probably choking on the object you are trying to send.
You should either send the data object directly:
data: data,
(to get $_POST['year'], etc. in php)
or convert the object to a json string you can decode on the php side:
data: { 'search': JSON.stringify(data) },
What does happen inside of find_blogposts()?
Alternatively you could try .post().
$.post( "repositories/blogposts.php", { year: "2013", month:"10", day:"1" }, function( data ){
// do something here
});
In your php just receive $_POST['year'] which will be 2013.
Hope it helps.
Here is api doc for .post()
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]);
I'm trying to load an array in my javascript. I need to send this array in some format to a PHP script that I'm going to call. In the example below, gSelectedMeds is my array. The value count will tell the PHP script how many meds items to expect to receive. I'm having trouble getting the data from the array into a format that I can send via the data option of $.ajax. Any help would be greatly appreciated!!
The part of the code below that is giving me grief at the moment is the data option:
$('#export').click(function() {
$.ajax({
url:'ajax-exportMeds.php',
data:
{"number":gSelectedMeds.length},
$.each(gSelectedMeds,
function(intIndex, objValue){
{"med"+intIndex:objValue},
}
),
type: "GET",
//dataType: "text",
success: function(data){
$('p#allMeds').text('');
$('a.bank').text('');
//clear array, bank and storedList divs
$(this).text('');
gSelectedMeds[] = '';
//$('ul#storedList').fadeOut('fast');
$('ul#storedList').text('');
return false;
},
}),
});
You should send the data as json. Then you can read it using json_decode() in php >= 5.2.0
I ended up stringing out the array and sending a count at the end of the url that I called:
$('#export').click(function() {
$.each(gSelectedMeds,
function(intIndex, objValue) {
i=intIndex + 1;
if(i>1) {string+='&';}
string+='med'+i+'="'+objValue+'"';
}
)
string += "&count="+i;
$.ajax({
url: 'ajax-exportMeds.php?'+string,
type: "GET",
dataType: "text",
success: function(data){
$('#dialog_layer').dialog({
autoOpen: true,
bgiframe: true,
modal: true,
closeOnEscape: true,
buttons: {
"OK": function() { $(this).dialog("close"); }
}
})
}
})
});