I’m having a problem validating a contact form

Asked

Viewed 73 times

0

Html code:

    <section class="contato">   
    <div class="parallax-targetaf section-0" data-parallax="scroll" data-image-src="img/4.jpeg">
    <div class="container cf">
    <div class="containerrr">  
  <form id="contact" action="mail_send.php" method="post">
    <h3>Precisa de Ajuda?</h3>
    <h4>Entraremos em contato em 24 horas úteis.</h4>
    <fieldset>
    <input required placeholder="Digite seu nome" type="text" name="nome" >
    </fieldset>
    <fieldset>
      <input required placeholder="Digite seu email" type="email" name="email">
    </fieldset>
    <fieldset>
      <input required placeholder="Deixe o seu numero (Opicional)" type="text"  name="telefone">
    </fieldset>
    <fieldset>
      <textarea required placeholder="Digite sua mensagem ...." name="mensagem"></textarea>
    </fieldset>
    <fieldset>
      <button name="BTEnvia" type="submit" id="contact-submit" data-submit="...Enviando">Enviar</button>
    </fieldset>
  </form>
</div>


                </div>
        </div>
        </section>

php code :

<?php

function pegaValor($valor) {
    return isset($_POST[$valor]) ? $_POST[$valor] : '';
}

function validaEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

function enviaEmail ($nome, $de, $telefone, $msg , $para, $email_servidor) {
    $headers = "From: $email_servidor\r\n" .
               "Reply-To: $de\r\n" .
               "X-Mailer: PHP/" . phpversion() . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

  mail($para, $assunto, nl2br($mensagem), $headers);
}

$email_servidor = "[email protected]";
$para = "[email protected]";
$nome = pegaValor("nome");
$de = pegaValor("email");
$telefone = pegaValor("telefone");
$msg = pegaValor("mensagem");


if (validaEmail($de) && $mensagem) {
enviaEmail($nome, $de, $telefone, $msg , $para, $email_servidor);
$pagina = "mail_ok.php";
} else {
$pagina = "mail_error.php";
}

header("location:$pagina");
?>

tested on my host site and only goes to mail_error.php page I don’t know why anyone could help me where I am missing?

And if someone could add an example of qnd clicking on "SEND", instead of opening a page appear an "Alert" in js or ajax. ( Email sent successfully or error) ..

1 answer

1


The error is because you are capturing the variable value $mensagem, but it doesn’t exist.

Substitute

if (validaEmail($de) && $mensagem) {

for

if (validaEmail($de) && $msg) {

and replace

mail($para, $assunto, nl2br($mensagem), $headers);

for

mail($para, $assunto, nl2br($msg), $headers);

Sending e-mail via javascript

Javascript:

<section class="contato">
  <div class="parallax-targetaf section-0" data-parallax="scroll" data-image-src="img/4.jpeg">
    <div class="container cf">
      <div class="containerrr">
        <form id="contact">
          <h3>Precisa de Ajuda?</h3>
          <h4>Entraremos em contato em 24 horas úteis.</h4>
          <fieldset>
            <input required placeholder="Digite seu nome" type="text" name="nome">
          </fieldset>
          <fieldset>
            <input required placeholder="Digite seu email" type="email" name="email">
          </fieldset>
          <fieldset>
            <input required placeholder="Deixe o seu numero (Opicional)" type="text" name="telefone">
          </fieldset>
          <fieldset>
            <textarea required placeholder="Digite sua mensagem ...." name="mensagem"></textarea>
          </fieldset>
          <fieldset>
            <button name="BTEnvia" type="button" id="contact-submit" data-submit="...Enviando">Enviar</button>
          </fieldset>
        </form>
      </div>
    </div>
  </div>
</section>

<script>
    /* Instancia o objeto para as requisições */
    const req = new XMLHttpRequest();

    /* Captura o botão de envio do form */
    const btnSubmit = document.querySelector("#contact-submit");

    /* Captura o form de contato */
    const formContact = document.querySelector("#contact");

    /* Adiciona o evento para capturar o resultado da requisição */
    req.addEventListener("loadend", function(result){

      /* Converte a resposta para JSON */
      var response = JSON.parse(result.target.response);

      /* Verifica o resultado e exibe o alerta */
      if (response.success) {
        alert("Mensagem de Sucesso");
      } else {
        alert("Mensagem de Falha");
      }
    })

    /* Adiciona evento para envio dos dados */
    btnSubmit.addEventListener("click", function() {
      var form = new FormData(formContact);

      /* Abre a conexão do tipo POST e assíncrona */
      req.open("POST", "envia-email.php", true);

      /* Envia os dados */
      req.send(form);
    })
</script>

PHP:

<?php

function pegaValor($valor) {
    return isset($_POST[$valor]) ? $_POST[$valor] : '';
}

function validaEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

function enviaEmail ($nome, $de, $telefone, $msg , $para, $email_servidor) {
    $headers = "From: $email_servidor\r\n" .
               "Reply-To: $de\r\n" .
               "X-Mailer: PHP/" . phpversion() . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

  mail($para, "Assunto", nl2br($msg), $headers);
}

$email_servidor = "[email protected]";
$para = "[email protected]";
$nome = pegaValor("nome");
$de = pegaValor("email");
$telefone = pegaValor("telefone");
$msg = pegaValor("mensagem");


if (validaEmail($de) && $msg) {
    enviaEmail($nome, $de, $telefone, $msg , $para, $email_servidor);
    $result = true;
} else {
    $result = false;
}

echo json_encode(["success" => $result]);
  • Opa valdeir I’m sorry for the delay bro I ended up sleeping, so if I put the email via javascript will not need this part php bro? And in case I would only need to call in form the js file or need to call after the head tb?

  • @Felipe did not understand. Sending via js, o - this code - php will be able to work with the data. The only thing that will change in your code php (beyond the above errors), will be the return, which will be in JSON.

  • Ah ok, like I said I would need in the form action to call this file. js isn’t that it? Also I would need to call this file in the head tb part?

  • In case the form would have to be like : <form id="contact" action="enviojs.js" method="post"> and I would have to create a file : send-email.php with this php code?

  • Got it. Just add the js inside the tag <script></script> and change the type from the Submit button to type="button". Anything I can post html code already with js code.

  • opa mano se tem como seria mt ajuda, mt obrigado. So js will work alone or in conjunction with php? Because I saw this : req.open("POST", "send-email.php", true);

  • 1

    Edited. The js will not work together with the php. This code you mentioned, serves to open a connection to then send the data. It’s basically the same thing as the action="envia-email.php", the difference is that the user will not leave the page.

  • opa mano tranquilo o method vc left calling the action="mail_send.php" this is right?

  • I forgot, but it will be ignored by the code. I modified the code.

  • and where would I put the mail from the server these things ? And I added the code and clicked send and nothing happened .

  • There was no Alert .

  • Blz @Valdeir obg.

Show 8 more comments

Browser other questions tagged

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