I have an array of Javascript objects, which I convert to a string using JSON.stringify() before processing with AJAX.
On the server side, all I am trying to do is verify that the proper $_POST["flavors"]
variable is set, and output it's contents. I have verified (via a simple conditional) that the $_POST["flavors"]
is being set, but I don't know how to modify the ajax call (or the PHP) to properly output it's contents.
- I have read on here that I (may) need to set the dataType for the $.AJAX call and/or set the header in my PHP script, but I wasn't sure if setting the header would be applicable since it is inside my functions.php file. *
(Array function)
flavors = [];
function wholesaleAJAX() {
var sizeSelect = $('form#wholesale-size-form input:checked');
if (sizeSelect.val() === 'regularBag') {
$('select[name="wholesale-flavors-regular"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-regular-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
} else if (sizeSelect.val() === 'largeBag') {
$('select[name="wholesale-flavors-large"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-large-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
}
(Stringify the array and process AJAX)
stringArray = JSON.stringify(flavors);
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: "returnHash",
flavors: stringArray
},
success:function(data){
$("#ajax").html(data);
}
});
(PHP for processing AJAX in functions.php)
function returnHash() {
if (isset($_POST["flavors"])) {
$flavors = json_decode($_POST["flavors"]);
print_r($flavors);
} else {
echo 'Not Set';
}
die();
}
add_action('wp_ajax_returnHash', 'returnHash');
add_action('wp_ajax_nopriv_returnHash', 'returnHash');
#ajax
, doesn't that work, and if so what exactly is the problem ? – adeneo Sep 2 '14 at 17:58