JS form with Success and Fail message

Asked

Viewed 190 times

1

for days I have been looking for a good tutorial, explaining from the beginning, middle and end to the creation of a form with sending (PHP and JS), but without giving Reload on the page and also where present an msg (div), in green if the email was sent correctly and in red, if no mandatory information has gone or been missing from the form.

Thank you in advance.

1 answer

1

Let’s put the following form, simple, which sends an email to the entered email and gives a simple return in 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’s a form, an input and a button with the type submit that when pressed triggers the event submit form that 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 are three different parts. The form.addEventListener intercepts the event submit and stops it with e.preventDefault(); for the page not having a refresh.

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

Finally the email is sent to the server. If you want to use this script you have to use your domain/url here. I have 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 return to Javascript Obrigado! that will be placed on the page to let the user know that everything is fine.

Completion:

Your question is bam ample and I leave an answer that works but only touches on the steps you have to take. You can read more here at Sopt about how to check emails in PHP, the mail function of PHP, login and passwords, how to avoid page refresh, etc... Take a look at the code and if you have problems I suggest you ask a question separately about the specific problem. Then it will be possible to answer in more detail.

Browser other questions tagged

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