Sending an Array by POST with JSON to PHP

Asked

Viewed 631 times

1

Next, I need to send an array by POST with JSON. I have read about JSON.stringify and in my PHP code use json_decode, but in practice I am not able to apply. I will put the code here and change it more or less with the idea that I hope, even wrong, but only to facilitate suddenly the understanding of logic.

HTML/Script

$("#ok").click(function() {
const nomes = ValorTextArea.value

var ArrayNomesComQuebraDeLinha = nomes.split('\n')   

    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'busca.php',
        data: ***ArrayNomesComQuebraDeLinha***
        async: true,
            success: function(dados){
                //Retorno da pagina busca.php, como os dados vao vir em ordem a ideia é colocar em uma table, se retornar o valor fica do lado, se nao fica vazio.
                nome   |idade
                junior |23
                joao   |N/A
            }

    });
  });  

PHP / SQL

include "conexao.php";

$nomes = $_POST['ArrayNomesComQuebraDeLinha']

for(var i=0; i< nomes.lenght;i++){
$select = "SELECT IDADE FROM clientes WHERE NOME" +$nomes[i];
$result = mysqli_query($conexao, $select);
while ($row = mysqli_fetch_assoc($result)) { 
$idade[] = array_map('utf8_decode', $row);
}
echo json_encode($idade);
}

I apologize if I could not be clear with the explanation or using the logic I hope along with my code. This is my first post.

From now on, thank you.

1 answer

1

First your javascript and php code contains mistakes, and possibly that’s why it’s not working.

The option date of function ajax jquery, receives parameters between keys and not by asterisk

Change the line:

data: ***ArrayNomesComQuebraDeLinha***

For:

data: { ArrayNomesComQuebraDeLinha },

Already in the PHP in the line of the variable $names receiving the data sent via POST foul semicolon change to:

$nomes = $_POST['ArrayNomesComQuebraDeLinha'];

Is also missing the sign of equal ( = ) which indicates that the column NAME must be = the variable $names[i]

In the PHP to concatenate string the signal shall not be used for +, is used dot

Thus remaining:

$select = "SELECT IDADE FROM clientes WHERE NOME = '" . $nomes[i] . "'";

Browser other questions tagged

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