Contact form with AJAX without refresh

Asked

Viewed 10,528 times

1

How to create a form with ajax that when pressing the send button it does not redirect you to another page but rather a message just below "Data sent".

Follow an example of code I’m studying, but this redirects you to another page in the case sendemail.php.

index php.

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

        <form name="contactform" method="post" action="sendemail.php">

            Nome: <input type="text" name="nome" /> </br>
            E-mail: <input type="text" name="email" /> </br>
            Assunto: <input type="text" name="assunto" /> </br>
            Menssagem: <textarea name="menssagem"></textarea>

            <input type="submit" value="Enviar Menssagem" />

        </form>

        </body>
        </html>

sendemail.php

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

<?php 

$nome = $_POST['nome'];
$email = $_POST['email'];
$assunto = $_POST['assunto'];
$menssagem = $_POST['menssagem'];


?>

<?php 

$to = "[email protected]";
$subject = "$assunto";
$menssagem = "<strong>Nome:</strong> $nome<br /><br /><strong>E-mail:</strong>$email<br /><br /><strong>Assunto:</strong> $assunto<br /><br /><strong>Menssagem:</strong> $menssagem ";
$header = "MIME-Version: 1.0\n";
$header .= "Content-type: text/html; charset=iso-8859-1\n";
$header .= "From: $email\n";
mail($to, $subject, $menssagem,$header);
echo "Enviado!";

?>


</body>
</html>

4 answers

2

You can just change put the target in the form

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

    <form name="contactform" method="post" action="sendemail.php" target="local_onde_sera_exibido_a_msg">

        Nome: <input type="text" name="nome" /> </br>
        E-mail: <input type="text" name="email" /> </br>
        Assunto: <input type="text" name="assunto" /> </br>
        Menssagem: <textarea name="menssagem"></textarea>

        <input type="submit" value="Enviar Menssagem" />
    </form>
    <iframe id="local_onde_sera_exibido_a_msg"></iframe>
    </body>
</html>

To do something really in AJAX you will need to do it in Javascript searching on the web vc think this (with pure JS) and that (with jquery)

2


You can do it, I took the name that you had in the form and put id:

HTML:

<form id="contactform" method="post" action="sendemail.php">

        Nome: <input type="text" name="nome" /> </br>
        E-mail: <input type="text" name="email" /> </br>
        Assunto: <input type="text" name="assunto" /> </br>
        Menssagem: <textarea name="menssagem"></textarea>

        <input type="submit" value="Enviar Menssagem" />
       <div id="resp"></div>
    </form>

JS:

$('#contactform').submit(function(e) {
    e.preventDefault();
    const nome = $('input[name="nome"]').val();
    const email = $('input[name="email"]').val();
    const assunto = $('input[name="assunto"]').val();
    const mensagem = $('textarea[name="mensagem"]').val();
    $.ajax({
        url: 'sendemail.php', // caminho para o script que vai processar os dados
        type: 'POST',
        data: {nome: nome, email: email, assunto: assunto, mensagem: mensagem},
        success: function(response) {
            $('#resp').html(response);
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });
    return false;
});
  • 1

    an interesting alternative and increases a little more the productivity would be to use the jquery method "Serializer()", it captures all fields of its form and abstracts the declaration/call of the fields in the function in the Submit() method. see documentation, it is very simple to use http://api.jquery.com/serialize/

  • Thanks @Leandromacedo , by the way I never used this method, how did he contact the variable data?

  • In this case it will remove the variables "name","email", etc , and in date it should look something like this: data: { $("#contactform"). serializer() }, , and in your php vc takes the fields by the name q assigned in the form

  • Ha good, I did not know, I’m tired of seeing but I never really used. Obagdo @Leandromacedo

  • haha. You can’t imagine

1

That would be it. You only need to include the jquery file if you haven’t used it yet.

    <form name="contactform" method="post" action="sendemail.php">

        Nome: <input type="text" name="nome" /> </br>
        E-mail: <input type="text" name="email" /> </br>
        Assunto: <input type="text" name="assunto" /> </br>
        Menssagem: <textarea name="menssagem"></textarea>

        <input type="button" value="Enviar Menssagem" id="enviar" />

    </form>
    <script>
       $("#enviar").click(function(){
       $.ajax({
           dataType:'html',
           url:"sendemai.php",
           type:"POST",
           data:({mensagem:$("input[name='nome']").val(),email:$("input[name='email']").val(),assunto:$("input[name='assunto']").val(),mensagem:$("input[name='mensagem']").val()}),

           beforeSend: function(data){ 

            }, success:function(data){
                alert("Dados Enviados");
            }, complete: function(data){}


           });
            });
    </script>
    </body>
    </html>

sendemail.php

$nome = $_POST['nome'];
$email = $_POST['email'];
$assunto = $_POST['assunto'];
$menssagem = $_POST['menssagem'];


$to = "[email protected]";
$subject = "$assunto";
$menssagem = "<strong>Nome:</strong> $nome<br /><br /><strong>E-mail:</strong>$email<br /><br /><strong>Assunto:</strong> $assunto<br /><br /><strong>Menssagem:</strong> $menssagem ";
$header = "MIME-Version: 1.0\n";
$header .= "Content-type: text/html; charset=iso-8859-1\n";
$header .= "From: $email\n";
mail($to, $subject, $menssagem,$header);
echo "Enviado!";

?>

1

In php // no head

JS with Jquery script js. jQuery(Document). ready(Function(){ jQuery('#Form_ws'). Submit(Function(){ by pressing(1); var data = jQuery( this ).serialize(); jQuery.ajax({ type: "GET", url: "sendemail.php", data: , ...

serialize takes the form fields and transforms into a get variable string sendemail.php receives the parameters via GET

Browser other questions tagged

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