Send data via the form without refresh

Asked

Viewed 77 times

0

Good evening, I have a comment script, and I wanted when the user sent the comment, it remained on the same page as it is, without upgrading to the php page. At the moment when it sends the question it is redirected to the php that processes the data. I tried via ajax, but it is still redirecting to php page.

<form method="post" action="insertcomment.php" id="form_comment">
        <h2 class="text-center text-muted" style="font-size: 18px;">Deixe um comentário:</h2>
      <div class="form-group">
        <input class="form-control" type="name" name="nome" value="<?= $_SESSION['nome'] ?>">
      </div>
      <div class="form-group">
        <textarea class="form-control" type="comentario" name="comentario" placeholder="Digite aqui seu comentário"></textarea>
      </div>
      <input class="form-control" type="hidden" value="<?= $_SESSION['id_usuario'] ?>" name="id_usuario">
      <input class="form-control" type="hidden" value="<?= $row['product_id'] ?>" name="product_id">
      <div class="form-group">
        <input type="submit" name="submit" class="btn btn-info mx-0 mx-auto text-center" value="Comentar">
      </div>
      <div id="resp"></div>
  </form>

<!---- SCRIPT DO FORMULARIO AJAX --->
<script> 
      $('#form_comment').submit(function(e) {
e.preventDefault();
const nome = $('input[name="nome"]').val();
const comentario = $('input[name="comentario"]').val();
const id_usuario = $('input[name="id_usuario"]').val();
const product_id = $('textarea[name="product_id"]').val();
$.ajax({
    url: 'insertcomment.php
', // caminho para o script que vai processar os dados
    type: 'POST',
    data: {nome: nome, comentario: comentario, id_usuario: id_usuario, product_id: product_id},
    success: function(response) {
        $('#resp').html(response);
    },
    error: function(xhr, status, error) {
        alert(xhr.responseText);
    }
});
return false;
});
  </script>

php page inserting data into MYSQL

<?php
require 'conexao_comment.php';

$nome = mysqli_real_escape_string($conn, trim($_POST['nome']));;
$comentario = mysqli_real_escape_string($conn, trim($_POST['comentario']));;
$id_usuario = mysqli_real_escape_string($conn, trim($_POST['id_usuario']));;
$product_id = mysqli_real_escape_string($conn, trim($_POST['product_id']));;

$sql = "INSERT INTO comentarios (id_usuario, product_id, nome, comentario) VALUES ('$id_usuario', '$product_id', '$nome', '$comentario')";
?>

2 answers

0

I made some changes to the form script one of which was adding an Event Listener. I did tests and worked perfectly by clicking the "comment" button the request is made, and the browser does not give more refresh when submitting the form.

<script>
window.addEventListener('load', function() {
  document.querySelector('#form_comment').addEventListener("submit", (e) => {
    // Cancela o evento ao submeter o formulário
    e.preventDefault();
    // Com o objeto FormData conseguimos pegar os valores do formulário
    const data = new FormData(e.target);

    // Enviado o formulário
    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
        document.querySelector('#resp').innerHTML = this.responseText;
      }
    });

    xhr.open("POST", "http://localhost/insertcomment.php");

    xhr.send(data);
  });
});
</script>
  • Data are not entered in the database.

0

You can send the form data by changing the send button and using Jquery as follows.

<input id="enviar" type="button" value="Enviar">

$('input#enviar').click(function () {
    $.post( 'url', $('form#form_comment').serialize(), function(data) {
        $('#resultadorelatorio').html(data.result);
        },'json'
    );
}
  • Didn’t work :(

Browser other questions tagged

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