Question:
I have a contact form where I send the information entered to my BD
, I would like to leave a message to the user after submitting the form and I am not having success, what I did was this:
I have a div
positioned above my form
, like this:
<div class="loader"></div>
When submitting the form
I validate the fields of the form
and send the message, it looks like this:
$(document).ready(function(){ // Scripts de submissão $('.contactForm').submit( function(){ //statements to validate the form var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var email = document.getElementById('e-mail'); if (document.cform.nome.value == "") { $('.nome-missing').css({'opacity': 1 }); } else {$('.nome-missing').css({'opacity': 0 });} if (document.cform.telefone.value == "") { $('.telefone-missing').css({'opacity': 1 }); } else {$('.telefone-missing').css({'opacity': 0 });} if (!filter.test(email.value)) { $('.email-missing').css({'opacity': 1 }); } else {$('.email-missing').css({'opacity': 0 });} if (document.cform.cidade.value == "") { $('.cidade-missing').css({'opacity': 1 }); } else {$('.cidade-missing').css({'opacity': 0 });} if (document.cform.uf.value == "") { $('.uf-missing').css({'opacity': 1 }); } else {$('.uf-missing').css({'opacity': 0 });} if (document.cform.assunto.value == "") { $('.assunto-missing').css({'opacity': 1 }); } else {$('.assunto-missing').css({'opacity': 0 });} if (document.cform.mensagem.value == "") { $('.mensagem-missing').css({'opacity': 1 }); } else {$('.mensagem-missing').css({'opacity': 0 });} if ((document.cform.nome.value == "") || (document.cform.telefone.value == "") || (!filter.test(email.value)) || (document.cform.cidade.value == "") || (document.cform.uf.value == "") || (document.cform.assunto.value == "") || (document.cform.mensagem.value == "")) { return false; } if ((document.cform.nome.value != "") && (document.cform.telefone.value != "") && (!filter.test(email.value)) && (document.cform.cidade.value != "") && (document.cform.uf.value != "") && (document.cform.assunto.value != "") && (document.cform.mensagem.value != "")) { // Mostrar a barra de carregamento $('.loader').append(); //send the ajax request $.post('processo.php',{ nome:$('#nome').val(), telefone:$('#telefone').val(), email:$('#e-mail').val(), cidade:$('#cidade').val(), uf:$('#uf').val(), assunto:$('#assunto').val(), mensagem:$('#mensagem').val() }, // Retornar os dados function(data){ // Oculta $('.loader').append(data).slideDown(800); }); // Espera 2000, em seguida, fecha o formulário e desaparece setTimeout('$(".resposta").slideUp(800)', 6000); // Permanecer na página return false; } }); });
My .php
looks like this:
$nome = $_POST['nome']; $email = $_POST['email']; $telefone = $_POST['telefone']; $cidade = $_POST['cidade']; $assunto = $_POST['assunto']; $mensagem = nl2br($_POST['mensagem']); $subject = $assunto; $body = "From $nome, \n\n$mensagem"; $headers = 'From: '.$email.'' . "\r\n" . 'Reply-To: '.$email.'' . "\r\n" . 'Content-type: text/html; charset=utf-8' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail("email@gmail.com", $subject, $body, $headers);
<div class="resposta">
<h4>Obrigado <?php echo $nome ?>!</h4>
<p>Em breve entraremos em contato com você.</p>
The css
of the answer div
looks like this:
.resposta { border-bottom: 1px solid #eee; padding-bottom: 15px; margin-bottom: 15px; }
Answer:
To start, think about doing the validation in PHP, calling a page via ajax, instantiating the class as below:
class SendEmail
{
private $nome;
private $email;
private $telefone;
private $cidade;
private $assunto;
private $mensagem;
private $receive_mail;
public function __construct($data)
{
$this->receive_mail = "email@gmail.com";
try
{
if (count($data) < 6) {
throw new Exception("Todos os dados devem ser preenchidos.");
}
if ($data['nome'] == "") {
throw new Exception("Preencha seu nome completo corretamente.");
}
if ($data['email'] == "") {
throw new Exception("Preencha seu e-mail corretamente.");
}
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL) === false) {
throw new Exception("Preencha um e-mail válido.");
}
if ($data['telefone'] == "") {
throw new Exception("Preencha seu telefone corretamente.");
}
if (!preg_match('/\([0-9]{2}\) [0-9]{4}\-[0-9]{4,5}/', $data['telefone'])) {
throw new Exception("Preencha um número corretamente, exemplo: (11) 1234-1234.");
}
if ($data['cidade'] == "") {
throw new Exception("Preencha a cidade corretamente.");
}
if ($data['assunto'] == "") {
throw new Exception("Preencha o assunto corretamente.");
}
if ($data['mensagem'] == "") {
throw new Exception("Preencha a mensagem corretamente.");
}
//envia a mensagem
return $this->sendMail();
} catch (Exception $e) {
return json_encode(array('success'=>'0','errors'=>$e->getMessage()));
}
}
public function sendMail()
{
$subject = $this->assunto;
$body = "From {$this->nome}, \n\n{nl2br($this->mensagem)}";
$headers = 'From: ' . $this->email . "\r\n" .
'Reply-To: ' . $this->email . "\r\n" .
'Content-type: text/html; charset=utf-8' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
if (mail($this->receive_mail, $this->assunto, $body, $headers)) {
return json_encode(array('success'=>'1','message'=>'Mensagem enviada com sucesso!'));
} else {
throw new Exception("Ocorreu um erro no envio da mensagem, por favor, tente mais tarde.");
}
}
}
if ($_POST) {
//aqui ele retornará um JSON com os erros ou a mensagem de sucesso
echo new SendEmail($_POST);
}
Now in javaScript, execute the method in ajax:
function sedMail() {
var data = {
nome:$('#nome').val(),
telefone:$('#telefone').val(),
email:$('#e-mail').val(),
cidade:$('#cidade').val(),
uf:$('#uf').val(),
assunto:$('#assunto').val(),
mensagem:$('#mensagem').val()
}
$.ajax({
url:'sendEmail.php',
method:'post',
dataType:'json',
data: data,
success: function(data) {
if (data.success) {
$('.success').text(data.message);
} else {
if (data.errors.length > 0) {
var errorsList = '<div class="errors-messages">\
<p>Corrija os erros abaixo:</p>\
<ul>';
for (var i in data.errors) {
errorsList+= "<li>- "+data.errors[i]+"</li>\n";
}
errorsList+= '</ul>\
</div>';
$('.errors').html(errorsList);
}
}
}
});
And in the view, just put where it will display the error messages and the success message:
<div class="errors"></div>
<div class="success"></div>