Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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');
share|improve this question
    
If your question is "how do I check what ajax is sending/receiving in my browser" the answer is "use the browser developer console and check the Network tab". –  James Sep 2 '14 at 17:56
    
There's no need to stringify anything, and you're already returning data to the ajax function and outputting it to #ajax, doesn't that work, and if so what exactly is the problem ? –  adeneo Sep 2 '14 at 17:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.