Ajax + PHP saving empty fields in the database

Asked

Viewed 38 times

-1

When I use only html and php (action) the data is successfully inserted in the database, but when I use ajax the data is saved with empty fields (including NOT NULL fields in the database). Could you help me find the mistake? Version of jquery: 3.5.1

HTML:

<form method="POST" id="cad-form" action="">
              <div class="form-group cad-container">
                <label>Qual o nome completo?</label>
                <input class="form-control" name="nome" placeholder="Nome e sobrenome">
                <label>E a data de nascimento?</label>
                <input inputmode="numeric" name="data-nasc" class="form-control um" id="cad-dat-nasc" placeholder="Ex: 01/01/2020">
                <label>Qual o telefone? </label>
                <input inputmode="numeric" name="telefone" class="form-control um" id="cad-tel"placeholder="Ex: (99) 9 9999-9999">
                <label>Onde mora? </label>
                <input class="form-control" name="endereco" placeholder="Rua, numero, bairro e cidade">
                <label>Qual o CPF?</label>
                <input inputmode="numeric" name="cpf" class="form-control um" id="cad-cpf" placeholder="Ex: 999.999.999-99">
                <label>E o RG?</label>
                <input inputmode="numeric" name="rg" class="form-control um" id="cad-rg"placeholder="Ex: 99.999999-9">
              </div>
              <!--o cad-btn deve estar dentro do formulario-->
              <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" id="volta-btn">Voltar</button>
                <button type="submit" class="btn btn-outline-primary" id="cad-btn">Cadastrar</button>
              </div>
            </form>

Javascript:

$(document).ready(function(){
  $('#cad-form').submit(function(){
    var dados = $(this).serialize();

    $.ajax({
      method: "POST",
      url: "cadastro.php",
      dataType: "json",
      data: {dados},
      success: function(data){
         console.log(data);
      },
      error: function() {
        alert("Não foi possível cadastrar, contate o suporte ténico! :(");
      }
    });
  });
});

PHP:

<?php
  $nome = $_POST['nome'];
  $dataNasc = $_POST['data-nasc'];
  $telefone = $_POST['telefone'];
  $endereco = $_POST['endereco'];
  $cpf = $_POST['cpf'];
  $rg = $_POST['rg'];

  if (empty($nome)) {
    $banco = mysqli_connect('127.0.0.1', 'root', '', 'luanaconsolini');
    $sql = "INSERT INTO cliente VALUES ('', '$nome', '$dataNasc', '$telefone', '$endereco', '$cpf', '$rg')";
    mysqli_query($banco, $sql);
    echo "Cliente cadastrado com sucesso!";

    echo "Nome: ".$nome;
  }
 ?>
  • You have a syntax error in data:{dados} you don’t have those keys.

  • I had modified this part a little after posting, but it did not help

  • the first problem is that EMPTY checks if the variable is empty and returns true when a variable is empty. When you submit the form obviously the $name variable will not be empty so it will not enter if (Empty($name)) {. To enter if deny EMPTY by placing an interjection before, if (!Empty($name)) { ie if the variable Is not empty.

2 answers

1

What is happening is that the Ajax request is being cancelled when submitting the form. Your code sends via Ajax and via form at the same time, sending by form makes the browser navigate to the action. To send only via Ajax, you need to cancel the standard form submission:

$(document).ready(function(){
  $('#cad-form').submit(function(event){
    event.preventDefault();

0

Pass the date parameter inside Ajax without keys.

The serialize() function already sends the data in the required format.

If you do not use serialize() then you pass the data between keys in JSON format

$(document).ready(function(){
  $('#cad-form').submit(function(){
    var dados = $(this).serialize();

    $.ajax({
      method: "POST",
      url: "cadastro.php",
      dataType: "json",
      data: dados, //Remova as chaves
      success: function(data){
         console.log(data);
      },
      error: function() {
        alert("Não foi possível cadastrar, contate o suporte ténico! :(");
      }
    });

    return false; //Adicione o RETURN FALSE para que seu form não seja enviado sem o AJAX. Desabilitando a função padrão do form que é fazer o request na pagina
  });
});

Browser other questions tagged

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