Form in JS with message of Success and Fail

1

I have been looking for a good tutorial for a few days, explaining the beginning, middle and end of the creation of a form with sending (PHP and JS), but without reloading the page and also where it presents a msg (div) in green if the email was sent correctly and red, if you did not go or missed some mandatory information on the form.

Thank you in advance.

    
asked by anonymous 21.06.2015 / 23:00

1 answer

1

Let's put the following simple form, which sends an email to the entered email and gives a simple return on the form saying "Thank you".

HTML:

<form action="">
    <label for="email">Escreva por favor o seu email</label>
    <input type="text" name="email" />
    <button type="submit">Enviar</button>
    <div id="avisos"></div>
</form>

Here you have a form, an input and a button with type submit that when pressed triggers the submit event of the form JavaScript will use / intercept.

JavaScript:

var form = document.querySelector('form');

function validar(email) {
    email = email.split(' ').join(''); // retirar espaços vazios
    if (!email) return false;          // caso email esteja vazio
    if (!email.match(/\S+@\S+\.\S+/)) return false; // verificação generalista
    return true;
}

function enviar(email, info) {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
            info.innerHTML = ajax.responseText;
        }
    }
    ajax.open('POST', 'http://seusite.com/enviar.php', true);
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.send('email=' + email);
}

form.addEventListener('submit', function (e) {
    e.preventDefault();
    var avisos = document.getElementById('avisos');
    var email = this.querySelector('input[name="email"]');
    var ok = validar(email.value);
    if (ok) return enviar(email.value, avisos);
    else return avisos.innerHTML = 'O email não está bem preenchido';
});

Here you have 3 different parts. The form.addEventListener intercepts the submit event and stops it with e.preventDefault(); for the page not to have a refresh.

Then send the email to a validar function that returns a Boolean to know if the email was ok or had problems. If it is OK, it sends to the function that makes the ajax request. Otherwise it gives the user an error.

By the end the email is sent to the server. If you want to use this script you have to use your domain / url here. I've now tested this code on my server and everything worked fine.

PHP:

<?php

$email = $_POST['email'];
// fazer mais verificações e adicionar à base de dados aqui...

$to      = $email;
$subject = 'Newsletter';
$message = 'Obrigado!';
$headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

$ok = mail($to, $subject, $message, $headers);
if ($ok) echo $message;
else echo 'Houver um problema com o envio de email...';
?>

Finally in PHP, very simple example, send an email to the email that was received and returns to the Obrigado! JavaScript that will be placed on the page so the user knows that everything is fine.

Conclusion:

Your question is wide bam and I leave an answer that works but only touches lightly on the steps you have to take. You can also read more here at how to check emails in PHP , the PHP mail function , login and passwords >, how to avoid page refresh , etc etc ... Take a look at the code and if you have problems I suggest that ask a separate question on the specific problem. There you will be able to respond in more detail.

    
21.06.2015 / 23:38