0

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');
2
  • 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". Commented Sep 2, 2014 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 ? Commented Sep 2, 2014 at 17:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.