How to pass a php array as a $.ajax data parameter?

Asked

Viewed 1,118 times

1

How to pass a php array as a $.ajax data parameter? Ex:

<?php $nomes = array('maria','joao','jose'); ?>

  $.ajax({
    url: 'pagina.php',
    dataType: 'json',
    method: 'POST',
    data: {'nomes' : <?php echo json_encode($nomes); ?>},
    sucesss: function(data){
      console.log(data);
           }
     });

And on the page pick up this array.

  • That code doesn’t make any sense to me. .-.

  • Use $variável = json_decode($_POST['nomes']);, this way you will have $variable[1], $variable[2], $variable[0].

  • The way you’re doing it is correct...

  • Well, from what I’ve noticed, because the php array does not contain Keys the json_encode function converts it to a normal javascript array. So in case maybe my question should be how to convert this js array to a php array by picking it up with $_POST on the target page. Thanks for the answers.

  • 1

    I don’t think it’s cool to mix jquery code with php, that’s gambiarra². Transform the array into json, then write it into an HTML element. capture the element value via jquery and hide it. Now I can’t formalize an answer, when I get home I try to post

  • Vlw by the answer Adriano, tbm do not like to do this way, so I posted the question here, I will try your tip. Abr.

Show 1 more comment

1 answer

-2

nomes = [];
nomes[0] = 'maria';
nomes[1] = 'joao';
nomes[2] = 'josé';


$.ajax({
   type: "POST",
   data: {nomes :nomes},
   url: "pagina.php",
   success: function(msg){
     console.log(data);
   }
});

  • 2

    welcome to SOPT, it is always interesting to explain what your code does, thus improving the understanding of the solution of the problem

Browser other questions tagged

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