Ajax does not send data to php!

Asked

Viewed 92 times

2

The code in Ajax works perfectly but the data is not sent to php! Where am I going wrong?

AJAX.php

<!DOCTYPE html>
<html>
    <head>
        <title>AJAX</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-3.4.1.min.js"></script> 
        <script type="text/javascript" src="AJAX.js"></script>
        <style>
            .comments{
                margin-left:400px;
                width: 400px;
            }
        </style>         
    </head>
    <body>
        <div class="cadastro"> 
            <form id="form-msg"  method="post" enctype="multipart/form-data">
                <fieldset>
                    <p>
                        <span>Digite seu comentário:</span>
                        <input type="textbox" id="mensagem">
                        <button type="button"> Clique  </button>
                    </p>  

                </fieldset>
            </form>   
        </div>     
            <p>Comentários</p>
            <span id="aqui"></span>     
        </div>

    </body>
</html>

AJAX_ACTION.php

<?php


$mensagem = $_REQUEST['mensagem'];
echo $mensagem;

AJAX.js


$(document).ready(function () {   
    $("button").click(function(){              
        var mensagem = $('#mensagem').val()
        if (mensagem == ''){
            alert("Comentário não pode ser vazio")
        }
        else{
            $.ajax({        
                type: 'POST',
                url: "AJAX_ACTION.php",
                data: {
                    mensagem: mensagem,


                },   
                dataType: "json",
                success: 
                    $("#aqui").append("<br>").append(mensagem),
                done:
                    $("#mensagem").val(''), 

            });                   
        }   
    });     
});  

  • 1

    How do you know you’re not sending?

  • I tried to change the Ajax url to "AJAX.php" and put the php code there, even then nothing happens, echo $message never prints anything.

  • I’ll rearrange everything for you. And then you’ll be readapted for your project ok?

  • Okay! Actually it’s just another test...

  • @Pedrohenrique check if it worked,

  • The problem is that you specified that the answer would be a JSON and your php returns a string without the JSON format that is refused. Put dataType: "text" who accepts.

Show 1 more comment

2 answers

1

Pedro, first I put everything in small letters for organization. Then I changed your function of onClick for submit putting this type in his button.

Follows index.php:

<!DOCTYPE html>
<html>
    <head>
        <title>AJAX</title>

        <style>
            .comments{
                margin-left:400px;
                width: 400px;
            }
        </style>         
    </head>
    <body>
        <div class="cadastro"> 
            <form id="form-msg" method="post" enctype="multipart/form-data">
                <fieldset>
                    <p>
                        <span>Digite seu comentário:</span>
                        <input type="textbox" id="mensagem">
                        <button type="submit" id="enviar"> Clique  </button>
                    </p> 
                </fieldset>
            </form>   
        </div>     
            <p>Comentários</p>
            <span id="aqui"></span>     
        </div>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="ajax.js"></script>
    </body>
</html>

2) Another change I made was to add your ajax.js below your form:

ajax.js

$('#form-msg').submit(function(e){
    e.preventDefault();

    if($('#enviar').val() == 'Enviando...'){
        return(false);
    }
    var mensagem = $('#mensagem').val()
    if (mensagem == ''){
        alert("Comentário não pode ser vazio")
    }
    else{
        $.ajax({
            url: 'ajax_action.php',
            type: 'post',
            dataType: 'html',
            data: {
                'mensagem': $('#mensagem').val()                
            }
        }).done(function(data){
            $("#aqui").append("<br>").append(data),

            $("#mensagem").val('')                                                                      
        });
    }
});

3) ajax_action.php:

<?php
    $mensagem = $_REQUEST['mensagem'];
        echo 'SEU ARQUIVO PHP: ' . $mensagem;

I hope I’ve helped.

  • +1, but I ask you to put dataType: 'text', even if today the return in html` does not suffer validation one day may suffer, as today is done with JSON, which in the future could invalidate your answer.

  • Leandro, the variable passed to php but is now not running the "done" ajax. Replace with Success and did not help either.

  • @Pedrohenrique What are you waiting for from . done?

  • @Leandroalfredo solved the question in the answer below, thank you.

1


You need to use the callback success, and instead of done, use complete. The callback of complete is executed after passing through the callback of the success:

,success: function(response){
   // faz algo aqui se deu tudo certo
}
,complete: function(){
   // faz algo aqui se deu tudo certo ou não
}

Note that the variable response (you can use the name you want) is what returns from the backend (in your example, the echo $mensagem; of PHP).

Remove the option dataType: "json", other than the success will not be executed if the return is not a valid JSON.

  • It is really necessary to use Function() and receive the value as argument in these cases?

  • If he wants to receive a response from the server, yes is required.

  • So without the echo of my php in this case the argument mensagem will have no value in the success? I thought the value of this variable was javascript related only. Now solved then.

  • The variable mensagem has the value that comes from var mensagem = $('#mensagem').val(). So far so good. However, if you want to receive some data from PHP, you need to use the function() (callback).

Browser other questions tagged

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