Why doesn’t the ajax work?

Asked

Viewed 240 times

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.

  • I just added

  • The date syntax is wrong. It would be: data:{mensagem:$("input[name='text']").val()},

  • Besides what @sam said, you need to add one return false by submitting the form. No event click, adds return false, so it won’t redirect.

  • Keys when closing the click event ?

  • Pedro, this "#send" was not set at any time in your form, your javascript is not being triggered.

Show 1 more comment

1 answer

1


Ajax acts 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, plus 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!"));

}

Further information can be found in the jQuery documentation.

http://api.jquery.com/jquery.ajax/

  • If I paste the action="post.php" into the form it sends, but updates the page and this error Parse error: syntax error, Unexpected ':', expecting ')' in /opt/lampp/htdocs/namorizando/app/rules/post.php on line 11;

  • Line 11 is: echo json_encode(array("type"=>"Success","title"=>"Success","text": "Challenge Successfully Completed!"));

  • I am placing the js code under jquery

  • without the action does nothing

  • Pedro, was with a syntax error in PHP, the communication between ajax and your PHP is happening because the error was pointed by the server. Tap "text": for "text" =>

  • another point also, this javascript code should be below your call to jQuery, at least in this order: <script src="jquery"> and then <script> code </script>. You also need to put an ID in your form, as the example.

  • this form ID must be the same used in the javascript event

Show 3 more comments

Browser other questions tagged

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