How to pass a Javascript Array to PHP [duplicate]

-1

How to pass Array newArray of Javascript to a vector in PHP? The idea is to get the id value of each checkbox and put it in a vector in PHP so that these id's are treated in a database (as primary key). This code already picks the id's from checked checkbox's and shows them in a window.

Example:

IDcheckbox: 1, 2, 3

VectorPHP: [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>
    
asked by anonymous 26.07.2018 / 17:01

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 DataType parameter tells you what type of data will be returned in the request, so your PHP should return a JSON, in the case of my example. And in data you will pass what you want to send in POST.

    
26.07.2018 / 18:04