Bobe
Bobe

Reputation: 2038

CodeIgniter - Post multiple arrays to controller

I have a dynamically generated form that allows users to enter new data and edit existing data. When the form is submitted, it collates the input values and groups them according to whether they are new or not, the former being denoted by class="new-entry".

So the function generates two arrays: updateData and insertData. Both arrays are of similar formats:

[
    0: {
        'id'    = 1,
        'value' = foo
    },
    1: {
        'id'    = 1,
        'value' = 'bar'
    },
    etc...
]

I am combining them into a new array object to send via ajax to the controller:

var postData = {
    'update_data': updateData,
    'insert_data': insertData
};

Then in the ajax call:

$.post(url, postData, function() { // some code });

However, in the controller, doing print_r($this->input->post()) or print_r($_POST) as a test only returns Array(). Even $this->input->post('update_data') returns nothing.

How can I retrieve these arrays in the controller?

Upvotes: 0

Views: 1518

Answers (1)

Saravanan
Saravanan

Reputation: 1889

Its not an issue with Codeigniter. Convert the array to proper JSON object (stringify) before you send.

Use

var postData = {
    'update_data': JSON.stringify(updateData),
    'insert_data': JSON.stringify(insertData)
};

$.post(url, postData, function() { // some code });

and in your controller, you can get by

$update_data=json_decode($this->input->post('update_data'));
$insert_data=json_decode($this->input->post('insert_data'));

Upvotes: 1

Related Questions