How to pass a Javascript Array to PHP

Asked

Viewed 534 times

-1

How to pass the Array newArray from Javascript to a PHP vector? The idea is to take the value id of each checkbox and put in a vector in PHP so that these id’s are treated in a database (as primary key). That code already takes checkbox id’s marked and shows them in a window.


Example:

Idcheckbox: 1, 2, 3

Vetorphp: [1,2,3]


function coletaDados() {
  var ids = document.getElementsByClassName('editar');
  coletaIDs(ids);
}

function coletaIDs(dados) {
  var array_dados = dados;
  var newArray = [];
  for (var x = 0; x <= array_dados.length; x++) {
    if (typeof array_dados[x] == 'object') {
      if (array_dados[x].checked) {
        newArray.push(array_dados[x].id)
      }
    }
  }
  if (newArray.length <= 0) {
    alert("Selecione um pelo menos 1 item!");
  } else {
    alert("Seu novo array de IDs tem os seguites ids [ " + newArray + " ]");
  }
}
<table border="1">
  <thead>
    <tr>
      <th>Id</th>
      <th>Nome</th>
      <th>Categoria</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input class="editar" type="checkbox" id="01" value="Barco"></td>
      <td>Barco</td>
      <td>Não definido</td>
    </tr>
    <tr>
      <td><input class="editar" type="checkbox" id="02" value="Carro"></td>
      <td>Carro</td>
      <td>não definido</td>
    </tr>
    <tr>
      <td colspan="3">
        <button style="width:100%;" onclick="coletaDados()">Editar</button>
      </td>
    </tr>
  </tbody>
</table>

  • Besides looking duplicated, your question is a little vague. You just showed the code, but did not give many details of what you intend to do.

  • @Wallacemaxters, the question has been edited. It’s clearer now?

  • Now it’s filet..

1 answer

0

Assuming you can use jQuery and a form is not an option, you can try the Ajax method:

$.ajax({
url: '/caminho/do/seu/script.php',
type: 'POST',
dataType: 'JSON',
data: newArray,
success:function(e){
    console.log(e);
},
error:function(error){
    console.log(error);
}});

When receiving this data in PHP it depends entirely on how the array was mounted in javascript.

In Ajax the parameter DataType says what kind of data will be returned in the request, so your PHP should return a JSON in the case of my example. And data you will pass what you want to send in the POST.

  • This is Felipe. Cool. But what’s in the field url? Also, this code can be used on the same page that contains the Javasript code?

  • In the url you must pass the url to your php that will receive the array. Ajax is a jQuery method, which in turn needs to be done in javascript.

  • Then you can put this code (AJAX) between the tag <script> </script> in the HTML file?

  • As long as jquery is already loaded, you can.

Browser other questions tagged

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