Why does ajax not work?

1

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: ../");
}
    
asked by anonymous 31.07.2018 / 16:03

1 answer

1

Ajax functions as an intermediary / communicator between your HTML and PHP. Through it you can update data from your page without necessarily updating it, can send data to your server by background, can bring more dynamism to your application, as well as several other utilities.

To communicate with your PHP, do the following:

<form id="form_text" name="form" 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">

    //capture o evento de envio do seu formulário
    $("#form_text").on("submit",function(e){

        //bloqueia acao principal
        e.preventDefault();

        //capture o  bloco que sofreu o evento
        var form = $(this);

        //localize a variavel
        var texto = form.find('textarea[name="text"]').val();

        //envie os dados para o seu php
        $.post('post.php',{ text:texto }).done(function(res){
            //O retorno do seu PHP ficará armazenado em "res".
            console.log(res);                

            //transforme a string retornada do PHP para um objeto javascript
            var response = JSON.parse(res);

            swal({type: response.type,title: response.title,text:response.text});

        }).fail(function(err){

            swal("Erro Fatal",{icon:'warning'});
        });
    });
</script>

Your 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)) {

    echo json_encode(array("type"=>"success","title"=>"Sucesso","text"=> "Desafio Concluído Com Sucesso!"));

} else {

    echo json_encode(array("type"=>"error","title"=>"Erro","text"=> "Erro ao concluir o desafio!"));

}

More information can be found in the jQuery documentation.

link

    
31.07.2018 / 17:28