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')";
?>
Data are not entered in the database.
– user172019