Post js array to php @jquery @codeigniter
i'm trying to pass a javascript array to a php controller ( i'm using codeigniter ) with ajax post method. Data seems to be sent but $_POST['data'] is not known. This is the code :
JAVASCRIPT:
function update_order(){
var ordre_column1 = $('#column1').sortable('toArray');
var data = serialize(ordre_column1);
$.post('../../controlleur_groupe_admin/ordre_box',data);
}
MY CONTROLLER:
function ordre_box() {
$data = $this->input->post('data')
$array = unserialize($data);
print_r($array);
}
I got no return in firebug, i'm wondering if content type is wrong:
Content-Type application/x-www-form-urlencoded; charset=UTF-8
thanks.
To simplify the code a bit :
Javascript :
function update_order(){
var ordre_column1 = $('#column1').sortable('toArray');
var data = ordre_column1.toString();
$.post('../../controlleur_groupe_admin/ordre_box',data);
}
Controller :
function ordre_box() {
echo $_POST['data'];
}
Firebug say :
Message: Undefined index: $data
But the post exists : Paramètresapplication/x-www-form-urlencoded 131,126,125,156,154 Source 1开发者_如何学Go31,126,125,156,154
How would you know that the key is 'data', wouldn't it be whatever you passed in the serialized string?
For example, if you had an array like this:
$array['value'] = 'hey!';
And you serialized this and sent it to the controller, you would retrieve that value like this:
$this->input->post('value');
Not like this, which I what I think you're trying to do but I might be wrong:
$array = $this->input->post('data');
echo $array['value'];
To fix it you could put the js array into another array with a key called data and then serialize that..
Ok, i found the solution! Here is the code ( with jquery.json-2.2.min.js ):
Javascript :
function update_order(){
var items=[]; // This common array will get all info for each item.
var ordre_column1 = $('#column1').sortable('toArray');
for (var i in ordre_column1){ //create an array for a single item
var item ={id: ordre_column1[i],
column_id: 1,
sort_no: i
};
items.push(item); // put the single item array in common array
}
var ordre1={ items: items };
$.post('../../controlleur_groupe_admin/ordre_box','data='+$.toJSON(ordre1)); //post the data to JSON format
}
The data are sent in JSON to the controller.
Controller :
function ordre_box() {
$data = $_POST['data'];
$json = str_replace('\\','',$data); //we replace all backslashes with nothing, which results in a correct json_decode string
$newdata = json_decode($json); // decode JSON format to php array
foreach($newdata->items as $item){ // Now i can use the data
echo " objet :";
echo $item->id;
echo ",";
echo $item->column_id;
echo ",";
echo $item->sort_no;
}
}
Thanks to Calle for putting me on the good way.
What's your serialize
function do? If it isn't moving that array to a string format you likely aren't going to see anything in your controller.
精彩评论