javascript – How to Post an Array via POST to a PHP Controller


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 didn't want to have to keep blowing up on the other side(Controller ).

I'm currently doing the following, Javascript:

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

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

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

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

But it arrives empty here.


The problem is in the JavaScript here:

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

You defined an array but are using it as an object/hash. Do like this:

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

Or like this:

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

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

Scroll to Top