Possible Duplicate:
multi-dimensional array post from form
I would like to send some data from the client to the PHP server using jQuery $.post()
. When it arrives at the server, I would like $_POST['myList']
to be equal to either of the following (what ever is easiest). What should I set the data object to within $.post()
?
array (
0=>array('id'=>123,'d1'=>'aaa','d2'=>'xxx'),
1=>array('id'=>234,'d1'=>'bbb','d2'=>'yyy'),
2=>array('id'=>345,'d1'=>'ccc','d2'=>'zzz')
)
array (
123=>array('d1'=>'aaa','d2'=>'xxx'),
234=>array('d1'=>'bbb','d2'=>'yyy'),
345=>array('d1'=>'ccc','d2'=>'zzz')
)
EDIT: first one looked like a simple array of objects, but seems jQuery needs this to be a keyed object:
var send_this = {
0: { id: 123, d1: 'aaa', d2: 'xxx' },
1: { id: 234, d1: 'bbb', d2: 'yyy' },
2: { id: 345, d1: 'ccc', d2: 'zzz' }
};
Second looks just has different looking keys for object containing objects:
var send_this = {
'123': { d1: 'aaa', d2: 'xxx' },
'234': { d1: 'bbb', d2: 'yyy' },
'345': { d1: 'ccc', d2: 'zzz' }
};
Tested implementation in jQuery 1.7.1:
$.post( '/herp.php', send_this, function(d) {
console.info( d );
});
The PHP program receives data exactly as you want it in $_POST.
You could send them as three arrays, one for each attribute.
myList_id[]=123&myList_d1[]=aaa&myList_d2[]=xxx&myList_id[]=234&...
In PHP, you will recieve them as $_POST['myList_id']
, $_POST['myList_d1']
and $_POST['myList_d2']
, which you could combine into your desired array.
Or if you include indices, you could go a step further:
myList[0][id]=123&myList[0][d1]=aaa&myList[0][d2]=xxx&myList[1][id]=234&...
which will give you the array directly: $_POST['myList']
You should use a JSON strong to send the data: Here is an example:
var pushData = {
id: "blalal",
id: "blalal",
id: "blalal",
};
JSON.stringify(pushData)
and then you can just post it or whatever
$.ajax({
url : "http://blalallalalal="+JSON.stringify(pushData),
type : "POST",
dataType: "text",
success: function (data) {
},
error: function() {
// alert("fsdf");
}
});
then from php side just use
$data = get_object_vars(json_decode($dataJSON));
DONE
If your using jQuerys $.post
or $.get
, you do not need to encode/decode, just pass a JS object as the data argument...
var data = {
"myList" : {
0 : {"id":1,...etc},
1 : {"id":2,...etc},
2 : {"id":3,...etc},
etc...
}
};
// post or get
$.post(
url2post,
data,
callbackFunc
);
Option 1
var data = [
{ id: 123, d1: 'aaa', d2: 'xxx' },
{ id: 234, d1: 'bbb', d2: 'yyy' },
{ id: 345, d1: 'ccc', d2: 'zzz' }
];
Option 2
var data = {
'123': { d1: 'aaa', d2: 'xxx' },
'234': { d1: 'bbb', d2: 'yyy' },
'345': { d1: 'ccc', d2: 'zzz' }
};
then
$.post(url, {mylist: data});