1
I have a code that does what I want, but refresh the page. I have tried several ways to use ajax to send the data to the database, but it still doesn’t work, and I have 3 questions about ajax:
1 - It is possible to create a session $_SESSION
using ajax?
2 - It is possible to use this created session?
3 - How ajax really works?
I’ve looked at a lot of websites, a lot of theories, a lot of code, but I’m still working on it, and I want to learn, but I need a light. What I would like is a sending name when I click the send button, and show the message I set in php.
I’m using bootstrap 4 css and js, and jQuery 3.3.1
Look at my code:
index php.
<form action="post.php" method="post">
<p class="text-muted">Obs: Envie uma texto.</p>
<textarea rows="3" class="form-control" name="text"</textarea>
<button type="submit" class="btn btn-success">Concluir</button>
</form>
<script type="text/javascript">
$("#enviar").click(function(){
$.ajax({
dataType:'html',
url:"post.php",
type:"POST",
data:({mensagem:$("input[name='text']").val(),
beforeSend: function(data){
}, success:function(data){
alert("Dados Enviados");
}, complete: function(data){}
});
</script>
And the post.php
<?php
session_start();
require_once("../../../assets/tools/config.php");
$text = $_POST['text'];
$sql = "INSERT INTO textos (text) values ('$text')";
$query = mysqli_query($conn, $sql);
//Verificar se salvou no banco de dados
if (mysqli_affected_rows($conn)) {
$_SESSION['msg'] = "<script>setTimeout(\"swal({type: 'success',title: 'Sucesso..',text: 'Desafio Concluído Com Sucesso!'})\", 100) </script>";
header("Location: ../");
} else {
$_SESSION['msg'] = "<script>setTimeout(\"swal({type: 'error',title: 'Erro..',text: 'Erro ao concluir desafio!'})\", 100) </script>";
header("Location: ../");
}
The ajax code is missing.
– Mauro Alexandre
I just added
– Pedro Henrique
The date syntax is wrong. It would be:
data:{mensagem:$("input[name='text']").val()},
– Sam
Besides what @sam said, you need to add one
return false
by submitting the form. No eventclick
, addsreturn false
, so it won’t redirect.– Mauro Alexandre
Keys when closing the click event ?
– Pedro Augusto
Pedro, this "#send" was not set at any time in your form, your javascript is not being triggered.
– Gabriel Carvalho