Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional Arrays via ajax to PHP

Ok seriously struggling here. I am having some problems trying to send a multdimensional array to PHP via ajax. Here's what I have been trying:

To simplify rather than copy paste a wall of code:

    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 to php via post. I figured I may aswell just join them together as I am multidimensional anyway thus :

    main_array['peoplearray'] = peoplearray;

now to do the 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 am just doing the following right now:

$data= $_POST['data'];
print_r($data);

in firebug: (an empty string)

when I have the var data = JSON.stringify(main_array); uncommented I get the following: [][

if i add $data = json_decode($_POST['data']); to the php I get:

Array ( )

Basically the main_array I realise does not need to be an array and so I can get that stuff across no problem but what I need to do is get the peoplearray over so that I can do some foreach etc... with it in php. Any help would be much appreciated I am sure I am just being stupid!

EDIT: The reasoning behind this is that peoplearray could have 0 or 100 entries so I just need to get it to php so I can foreach it to do the DB inputs. If there is a better approach I would be very grateful to hear it as I am still pretty new to this.

EDIT: Thanks to Nicola's answer everything is passing fine except the important part which is mainarry.peoplearray - it is not appearing in the the return console.log and I cant access it in PHP. Any solutions on this or do I have to put the foreach intelligence in the javascript and just send everything individually?

like image 691
Zac Avatar asked Mar 30 '12 15:03

Zac


1 Answers

First of all main_array is not an array but an object because in javascript there are no associative arrays and for this reason

main_array['peoplearray'] = peoplearray;

is equivalent to

main_array.peoplearray = peoplearray;

and you should declare main_array like this

var main_array = {};

then try to change your function like this:

var send = $.ajax({
        type: "POST",
        dataType: "json",
        cache: false,
        url: "theurl",
        data: {data:main_array} 
});

and server side

header('Content-type: application/json');
$data= $_POST['data'];
echo json_encode($data);
like image 138
Nicola Peluchetti Avatar answered Sep 18 '22 01:09

Nicola Peluchetti