I have a code that does what I want, but refreshes the page. I have tried in many ways to use ajax to send the data to the database, but it still does not work, and I have 3 questions about ajax:
1 - Is it possible to create a $_SESSION
session using ajax?
2 - Is it possible to use this created session?
3 - How does ajax really work?
I've looked at various websites, various theories, and codes, but I'm still crawling on it, I want to learn, but I need a light. What I would like was a submitting name when I clicked on the submit button, and it displayed 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: ../");
}