Ok seriously fighting here. I am having trouble trying to send a multidimensional array to PHP via ajax. Here is what I tried:
To simplify rather than copy paste into the code wall:
peoplearray[0] = [name] => 'john' [age] => '28' [sex] => 'Male' peoplearray[1] = [name] => 'julie' [age] => '20' [sex] => 'Female' main_array['item'] = 'x'; main_array['something'] = 'x'; main_array['another'] = 'x';
I want to get this in php via post
. I figured I could just join them together since I am multi-dimensional:
main_array['peoplearray'] = peoplearray;
now do ajax:
// var data = JSON.stringify(main_array); var send = $.ajax({ type: "POST", cache: false, url: "theurl", data: {data:main_array} //I do change this `main_array` when using the above stringify! }); send.done(function(msg) { console.log(msg); })
in PHP I'm just doing the following right now:
$data= $_POST['data']; print_r($data);
in firebug: (an empty string)
when I have var data = JSON.stringify(main_array);
uncommented, I get the following: [][
if I add $data = json_decode($_POST['data']);
in php, I get:
Array ( )
In principle, main_array
, I understand, does not have to be an array, so I can get this stuff without problems, but I need to make peoplearray
so that I can do several foreach
, etc ... with it in php. Any help would be greatly appreciated, I'm sure I'm just stupid!
EDIT: the argument for this is that peoplearray
can have 0 or 100 entries, so I just need to get it in php so that I can foreach
use it for DB inputs. If there is a better approach, I would be very grateful for this, as I am still pretty new to this.
EDIT: Thanks Nicola, answer that everything goes fine except for the important part, which is mainarry.peoplearray - it does not appear in the reverse console.log
, and I cannot access it in PHP. Any solutions on this or should I put foreach intelligence in javascript and just send everything individually?