Trying to send an array from jquery to PHP function - php

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

Related

Pass Boolean Values from Ajax to PHP

I've read a tonne of questions on the subject but none of them seam to solve my particular issue – I guess there's something wrong with the way I've formatted my array of objects in JS. Here's my Ajax function:
var marketing_prefs = [];
$('#save-marketing-prefs input').each(function() {
var tmp_array = {};
tmp_array['marketing_permission_id'] = $(this).val();
if ($(this).prop('checked')) {
tmp_array['enabled'] = 1;
} else {
tmp_array['enabled'] = 0;
}
marketing_prefs.push(tmp_array);
})
console.log(marketing_prefs);
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: marketing_prefs
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
What I'm doing is looping through a simple form with three checkboxes and creating an array of objects which will then go off to Mailchimp. My data arrives intact but the problem is that my boolean values come over to PHP as strings. I've switched from using true and false which was coming over as "true" and "false", to using 1 an 0 but those come over as strings too.
I suppose I could loop through the data and build a new array in PHP but the data is so close to being correct when it arrives that it seems like it must be unnecessary.
How can I get my data over as non-strings?
POST data is sent as simple name=value pairs, there's no syntax to specify datatypes, and everything is parsed as strings.
You can call intval($_POST['marketing_prefs'][$i]['enabled']) to convert it to an integer.
Another option is to convert the marketing_prefs array to JSON.
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: JSON.stringify(marketing_prefs)
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
Then in the PHP you can do:
$marketing_prefs = json_decode($_POST['marketing_prefs'], true);
Since, as Barmar stated, GET/POST can't specify data types (that's a rant in and of itself), one way would t be to cast it.
Very rough example:
var_dump((bool) <variable>);
The issue is if it's anything but 'true', 'empty' or I believe 0 it will return true. I'm in a hurry else I'd flush it out for you better.

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

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.

JQuery + Json - first steps with an example

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";

Categories