Ajax does not work - send PHP data without refresh

Asked

Viewed 2,413 times

2

I’m trying to send merged data from a form + PHP variables to be inserted into the BD, without there being page refresh.

For this, I have a simple html form, and a PHP conditional that checks the Submit click of this form (that’s because I have other submits on the same page). Inside IF, I inserted my AJAX to take this data to the file that I would write to BD.

The HTML form:

<form id="textoResp" action="" method="post">
    <label for="textoResposta">Digite sua resposta abaixo:</label>
    <textarea name="textoResposta" required></textarea>
    <input type="submit" name="text" />
</form>

The PHP snippet with Ajax is:

<?php                   
    if(isset($_POST['text'])):
        $id_servico = $_GET['servico'];
        $id_sessao = $_GET['id'];
        $id_pergunta = $r['id'];
        $id_user = $_SESSION['usrid'];
        $texto = $_POST['textoResposta'];

?>
     <script type="text/javascript">
        $(document).ready( function(){
            $("#textoResp").submit( function() {
                $.ajax({
                    type:'post',
                    url:'processa.php',
                    data:{ 'id_servico': <?php echo $id_servico; ?>, 'id_sessao': <?php echo $id_sessao; ?>, 'id_pergunta': <?php echo $id_pergunta; ?>, 'id_user': <?php echo $id_user; ?>, 'texto': <?php echo $texto; ?> },
                    success: function( data )
                    {
                        alert( data );
                    }   
                });
                return false;
            });
        });

    </script>                           
    <div class="status"><?php echo "Resposta Enviada!";?></div>                         
<?php
    endif;                  
?>

And the file processes.php, which would receive the data:

<?php

   $nid_servico = $_POST['id_servico'];
   $nid_sessao = $_POST['id_sessao'];
   $nid_pergunta = $_POST['id_pergunta'];
   $nid_user = $_POST['id_user'];
   $ntexto = $_POST['texto'];

   $link = mysql_connect("localhost", "root", "");
   mysql_select_db("db", $link);

   $sql1="INSERT INTO resposta(id_servico, id_sessao, id_pergunta, id_user, texto) VALUES ('$nid_servico', '$nid_sessao', '$nid_pergunta', '$nid_user', '$ntexto')";
   $executa_sql=mysql_query($sql1) or die(mysql_error());   

?>

What happens when I run this page: the data is filled in the Ajax code block in the browser, but the page gives refresh (the line "Return false;" would be to prevent refresh), and apparently the data does not arrive until PHP processes.php, as there is no recording in the BD and neither displays Alert of the data by Ajax. Where is the error?

2 answers

1


so that no refresh on your page failed to pass the event parameter, follows the code:

$(document).ready( function(){
        $("#textoResp").submit( function(ev) {
            ev.preventDefault();
            $.ajax({
                type:'post',
                url:'processa.php',
                data:{ 'id_servico': <?php echo $id_servico; ?>, 'id_sessao': <?php echo $id_sessao; ?>, 'id_pergunta': <?php echo $id_pergunta; ?>, 'id_user': <?php echo $id_user; ?>, 'texto': <?php echo $texto; ?> },
                success: function( data )
                {
                    alert( data );
                }   
            });
        });
    });

With this I hope to solve your refresh problem, but I think it will not work, because you need to take the values of the inputs form with jQuery or javascript to pass as date in ajax, a look at: https://api.jquery.com/serialize/.

Abs.

  • on the refresh, I’ve already changed to e.preventDefault(); but, as you said yourself, it didn’t work. Now, I don’t know exactly how to use the serialize(), because not only do I have form data, but I take all the data and convert it into PHP variables (because most come from the PHP block). How could it be in this case?

  • 1

    In this case, you could do it in two ways, the first way is simpler. You can include fields <input type='hidden' value='<?php echo $variavel_php ?>'> and make it serialize. The other way, is you put the variables in an array and turn into a JSON, and the javascript file use the function getJSON() from jQuery to take these values and after that make the ajax request.

0

Exchange this: <input type="submit" name="text" />

That’s why <input type="button" id="envia" name="text" />

And in the ajax exchange this: $("#textoResp").submit(function()

That’s why:

$("#envia").on('click', function()

Is this happening because you’re using the submit.


PHP

Trade this if, for that:

if($_SERVER['REQUEST_METHOD'] == "POST")

  • if you replace type by button, apparently PHP does not understand that the form is defined (line if(isset($_POST['text'])):). I realize this because now the values inside Ajax are no longer printed in the browser, and there is no writing in the BD (only refresh stopped).

  • I edited my pole.

  • The exchange had no effect... Besides, maybe this way I won’t be able to indicate actions for the other submits I have on the same page. That’s right?

  • No, you can do whatever you want... Bro, sorry. I messed up the jQuery code. I fixed the post, the line was wrong on ajax I put, check again...

  • I tried again, in two ways: as you suggested -> $("#envia").on('click', function() and also another way -> $("#envia").click(function()... But nothing yet. Nor is filling in the browser anymore... With Submit it continues only filling the data in the browser, but gives refresh

Browser other questions tagged

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