So, you’re doing some WordPress AJAX. And maybe you’re serializing your form data into an array of objects. JSON.stringify() and fire that into wp-ajax.php. And maybe you console.log‘d it to verify it’s an array of objects… Cool.

Maybe it looked like this (i.e. an array of objects):


[{"name":"event_name","value":"My cool Title"},{"name":"event_start_date","value":"2015/08/06"},{"name":"event_start_time","value":"12:30:AM"},{"name":"event_end_date","value":"2015/08/06"},{"name":"event_end_time","value":"01:00:AM"}]

But then in functions.php, you json_decode() your lovely $_POST[] data only to find PHP warning you that it’s not an array? “Invalid argument supplied foreach()“?? Heads will roll!!


$form_data = json_decode( $_POST['formData'] );
// my awesome array of objects, verified through the console beforeSend...
foreach($form_data as $form_data_point) {
// throws the damn warning: Invalid argument supplied foreach() !!!
}

Yeah, I got that too.

Google gave me a bunch of StackOverflow and WordPress support articles, which all suggested the wrong thing (for me, at least). They point to adding “true” as a parameter into json_decode(), which only turns your array of objects into an array of associative arrays. Or they tell you to use PHP’s is_array() or is_object() conditional checks on the $_POST[] data.

None of it worked. PHP just didn’t know it was an array. Some articles suggested PHP’s nearly-deprecated magic-quotes was on. Nope. It was off. Finally after getting the $_POST[] data and taking a look, I could see the culprit (a bunch of added slashes):


[{\"name\":\"event_name\",\"value\":\"My cool Title\"},{\"name\":\"event_start_date\",\"value\":\"2015/08/06\"},{\"name\":\"event_start_time\",\"value\":\"12:30:AM\"},{\"name\":\"event_end_date\",\"value\":\"2015/08/06\"},{\"name\":\"event_end_time\",\"value\":\"01:00:AM\"}]

With all those slashes added, that’s why the output is often “null” when folks get the data outputted.

My solution: PHP’s stripslashes() to the rescue.

Get rid of the slashes first, then json_decode():


$form_data = json_decode( stripslashes($_POST['formData']) );
// look above. we strip the slashes before json decoding
foreach($form_data as $form_data_point) {
// now we can finally do something with this friggin data...
}

Now you’re dancin’. Hope this helps your project. Let me know if it did!