Send JSON to PHP8 via AJAX

Asked

Viewed 25 times

1

I need a lot of help. I need to send a JSON to PHP via AJAX/Jquery but something is not working. I have a JS file with the command:

$('#save').click(function(e) {
    submit();
});


function submit() {
    let json = $('#textarea').text();
    let value = {values: json}
    $.ajax({
    method: "post",
    url: "server.php",
    dataType: 'json',
    data: JSON.stringify(value),
    beforeSend:  e => console.log(),
    success: e => console.log(e)
    });
};

And another PHP that gets what AJAX sends

if (file_get_contents("php://input")) {
    $dados = file_get_contents("php://input", true);
    $obj = json_decode($dados);
    print_r($obj->values);
gravar($obj);
};

gravar($data);
  function gravar($obj){
    global $conection;
      foreach ($obj->pessoas as $key => $value) {
        $insert_pessoa = "insert into pessoas(nome)values(:nome_pessoa)";
        $insert = $conection->prepare($insert_pessoa);
        $insert->bindParam(':nome_pessoa', $value->nome);
        $insert->execute();
      };
  };

The data contained in JSON will be used to write to DB and that is where the problem lies. I have a textarea with a string that will be sent via AJAX to PHP which in turn will process it and then save it to DB. Note that at the end of the AJAX code we have a PHP return. I get this return perfectly well however, the information contained in JSON is not recorded in DB.

Think of it this way: Consider the string of the textarea to be

'{"pessoas":[{"nome":"José","filhos":["a","b","c"]},{"nome":"Maria","filhos":["d","e","f"]}]}'

If I do it this way then it works:

if (file_get_contents("php://input")) {
    $dados = file_get_contents("php://input", true);
    $obj = json_decode($dados);
    print_r($obj->values);
    //gravar($obj);
  };

$myjson = '{"pessoas":[{"nome":"José","filhos":["a","b","c"]},{"nome":"Maria","filhos":["d","e","f"]}]}';
$data = json_decode($myjson);
gravar($data);
function gravar($obj){
    global $conection;
    foreach ($obj->pessoas as $key => $value) {
      $insert_pessoa = "insert into pessoas(nome)values(:nome_pessoa)";
      $insert = $conection->prepare($insert_pessoa);
      $insert->bindParam(':nome_pessoa', $value->nome);
      $insert->execute();
      };
  };

Would someone please help??

  • Have you checked if an error is not occurring in the query ? execute returns a boolean value, try to validate see if an error occurred with $Insert->errorInfo();

No answers

Browser other questions tagged

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