How to send an Array via POST to a PHP controller

Asked

Viewed 7,182 times

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 didn’t want to keep giving it explodes on 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 am recovering this way(Codeigniter):

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

But the same comes empty here.

2 answers

7


The problem is in Javascript here:

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

You defined a array but is using as if it were an object/hash. Do so:

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

Or so:

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

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

  • Valeeu, I’ll test tomorrow at work

  • It worked perfectly! Thank you very much!

2

I would pass the data as object itself, and recover them in PHP with the function json_decode() transforming them into a php array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.