How to send an Array via POST to a PHP controller

6

I need to pass an array via POST to my PHP controller, the only way I have in mind is not to pass an array, but to pass the information through a separator (,; |), but I did not want to have to keep blowing up the other side (Controller).

At the moment I'm doing the following, Javascript:

 var listaEnvioArray = new Array();
 var item = new Array();
 item["id"] = 1;
 item["descricao"] = "teste";
 listaEnvioArray.push(item);

 $.post(basepath + "perfil/meuController", {
    array : listaEnvioArray
    }, function(dados) {    
        // TODO ação
    });

In my controller I'm recovering this way (CodeIgniter):

$dados['array'] = $this->input->post('array');

But the same thing comes empty here.

    
asked by anonymous 27.02.2014 / 22:06

2 answers

7

The problem is in JavaScript here:

var item = new Array();
item["id"] = 1;
item["descricao"] = "teste";

You have defined an array but you are using it as if it were a / hash object. Here's how:

var item = {};
item["id"] = 1;
item["descricao"] = "teste";

Or so:

var item = { id: 1, descricao: "teste" };

Array in JavaScript is not equal to PHP. You can not use alpha-numeric keys. Only objects can have properties that are text ("id", "description"). In JavaScript, Arrays only have numeric keys, and we can not interfere with them freely as we can in PHP.

    
27.02.2014 / 22:10
2

I would pass the data as an object itself, and retrieve it in PHP with the json_decode() function turning them into php array.

    
28.02.2014 / 01:10