1
I’m having trouble getting the array I’m sending via Ajax, I know it’s sending all the indexes, but I’m having doubts about how I’ll receive and treat reading this array in the "gravar_btn.php" documentI put an example code and I will leave the image of how the page is in the browser below. The goal is to collect the information contained in the array and record it in the database.
function atualiza() {
var indices = [];
//Pega os indices
$('#cotacoes thead tr th').each(function () {
indices.push($(this).text());
});
var arrayItens = [];
//Pecorre todos os produtos
$('#cotacoes tbody tr').each(function (index) {
var obj = {};
//Controle o objeto
$(this).find('td').each(function (index) {
obj[indices[index]] = $(this).text();
});
//Adiciona no arrray de objetos
arrayItens.push(obj);
});
//Mostra dados pegos no console
console.log(arrayItens);
//Envia para o php
$.ajax({
type: "POST",
url: "gravar_btn.php",
data: arrayItens,
success: function(result){
alert("Envio realizado com sucesso!");
},
});
}
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<table id="cotacoes"> <!-- Tabela de exemplo -->
<thead>
<tr>
<th>Nome</th>
<th>Telefone</th>
<th>Endereço</th>
<th>Cep</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ricardo</td>
<td>(21) 9999-9999</td>
<td>Rua Dois, casa 3.</td>
<td>99999-999</td>
</tr>
<tr>
<td>Silvia</td>
<td>(21) 9999-9999</td>
<td>Rua Um, casa 2.</td>
<td>99999-999</td>
</tr>
</tbody>
</table>
<form action="gravar_btn.php" method="POST">
<button class="button is-block is-small" onclick="atualiza();">Enviar</button>
</form>
</body>
I don’t know what you’re calling "treat," but whatever you need to do with the data coming from ajax, do it inside the callback of "Success".
– bfavaretto
I need to write the information of the array in the database, but I’m not very familiar with javascript, inside the callback "Success" I can build a loop to read the array and save the data in the database? In this case the url: "save bt_btn.php" would be empty?
– Lucas
This part you do in php, not js
– bfavaretto
So, the part of the loop that will record the information in the database I already did, I’m just not able to get the array in the document "gravar_btn.php", what would be the code that receives the array in "gravar_btn.php"? (I’m starting now in this area of development, so I’m kind of layy for some kkk things)
– Lucas
From a print_r($_POST) in your php to see the received data.
– bfavaretto
I managed to solve with your tips, thank you very much for your help! :)
– Lucas