Success message after sending message by form

Asked

Viewed 369 times

0

I want a message to appear after filling the form and clicking on the "send" button stating that the content was successfully sent on the same page!

I’ll put in my code, thank you for your help.

                            <div class="contact_form_container">
                                <form method="post" action="email.php" class="contact_form">
                                    <div class="row contact_form_row">
                                        <div class="col-md-6">
                                            <input id="nome" name="nome" type="text" class="contact_input" placeholder="Nome" required>
                                        </div>

                                        <div class="col-md-6">
                                            <input id="email" name="email" type="email" class="contact_input" placeholder="e-mail" required>
                                        </div>

                                        <div class="col-12">
                                            <input id="assunto" name="assunto" type="text" class="contact_input" placeholder="Assunto" required>
                                        </div>

                                        <div class="col-12">
                                            <textarea id="msg" class="contact_input contact_textarea" name="mensagem" placeholder="Mensagem" required></textarea>
                                        </div>
                                    </div>
                                    <button id="enviar" type="submit" value="ENVIAR" onClick="Enviar();" class="contact_button">ENVIAR</button>
                                </form>
                            </div>

and php, which is being directed to another page

<?php

$para="[email protected]";
$subject="Contato pelo site";   

$nome= $_REQUEST['nome'];
$email= $_REQUEST['email'];
$assunto= $_REQUEST['assunto'];
$msg= $_REQUEST['mensagem'];

$enviar="<strong>Mensagem de contato</strong><br><br>";
$enviar.="<br><strong>Nome: </strong> $nome";
$enviar.="<br><strong>email: </strong> $email";
$enviar.="<br><strong>Assunto: </strong> $assunto";
$enviar.="<br><strong>Mensagem: </strong> $msg";

$header="Content-Type: text/html; charset- utf-8\n";
$header.="From: $email Replay-to: $email\n";


$mail = mail($nome,$email,$assunto,$msg);
if($mail){
    echo("Enviado com sucesso!");
}else{
    echo("Erro!");
}

?>
  • You can do this with AJAX.

  • use AJAX for this, and for it is better readable change $_REQUEST for $_POST

2 answers

2

Hello @Julianygarcia, welcome to Stackoverflowpt, there "n" ways to do this, using ajax, and posting directly on the page.

I would recommend you to study Javascript, which is a client-side language. I believe using ajax, is a better way to send data as it avoids page reloading unnecessarily.

It is also important to consider the validation of the form, so that it does not arrive incomplete, and validate the email so that the function email() do not return an error.

I would recommend instead of using the mail function, to use a library type Phpmailer, so you don’t run the risk that your form will stop working if your server deactivates the function for security reasons.

I will present two solutions, and you see which one you prefer, for the first form I will put a conditional on the page, and all the content on the same page:

1) SOLUTION (Basic POST method):

Save your page as php contact. and put a condition of POST:

<?php

if ($_POST) {
   $err= false;
   if($_POST['nome'] == ""){
    $err = true;
     echo " - O nome precisa ser preenchido.<br>";
   }
   if(($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) || !$_POST['email']){
    $err = true;
     echo " - preencha um email válido.<br>";
   }
 if ($_POST['assunto'] == ""){
    $err = true;
     echo " - preencha o assunto.<br>";
 }
  if ($_POST['mensagem'] == ""){
     $err = true;
     echo " - preencha sua mensagem.<br>";
  }
  if (!$err) {
     $para="[email protected]";
     $subject="Contato pelo site";   

     $nome= $_POST['nome'];
     $email= $_POST['email'];
     $assunto= $_POST['assunto'];
     $msg= $_POST['mensagem'];

     $enviar="<strong>Mensagem de contato</strong><br><br>";
     $enviar.="<br><strong>Nome: </strong> $nome";
     $enviar.="<br><strong>email: </strong> $email";
     $enviar.="<br><strong>Assunto: </strong> $assunto";
     $enviar.="<br><strong>Mensagem: </strong> $msg";

     $header="Content-Type: text/html; charset- utf-8\n";
     $header.="From: $email Replay-to: $email\n";

     $mail = mail($nome,$email,$assunto,$msg);
     if ($mail) {
        echo "<p>Enviado com sucesso!</p>";
     } else {
        $err = true;
        echo "<p>Ocorreu um erro no servidor</p>";
     }
  }
} else {
   echo "<p>Por favor, preencha o formulário abaixo:</p>";
}

?>

 <div class="contact_form_container">
    <form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>" class="contact_form">
        <div class="row contact_form_row">
            <div class="col-md-6">
                <input id="nome" name="nome" type="text" class="contact_input" placeholder="Nome" required>
            </div>

            <div class="col-md-6">
                <input id="email" name="email" type="email" class="contact_input" placeholder="e-mail" required>
            </div>

            <div class="col-12">
                <input id="assunto" name="assunto" type="text" class="contact_input" placeholder="Assunto" required>
            </div>

            <div class="col-12">
                <textarea id="msg" class="contact_input contact_textarea" name="mensagem" placeholder="Mensagem" required></textarea>
            </div>
        </div>
        <button id="enviar" type="submit" value="ENVIAR" class="contact_button">ENVIAR</button>
    </form>
</div>

2) SOLUTION (ajax method):

We will create an upload method (some people like to use a library called jquery, but I prefer to use pure javascript, ES5 or ES6).

When you submit the form, you will continue on the page and send the data by ajax in json format, as soon as php handles it on the server side (server-side), you will receive in the scope of your method the return in the format you requested in your xhr.responseType, in case a json:

    <script>

     document.addEventListener("DOMContentLoaded", function(event) {
      //depois que o dom for lido


        function sendForm() {

           var resultBox = document.querySelector('#message');

            //AQUI VOCÊ RECEBE OS DADOS DO SITE DOIS
            if (xhr.readyState == 4) {
                if (xhr.status == 200 && xhr.response.status) {
                      resultBox.innerHTML = '<div class="alert alert-success" role="alert">' + xhr.response.message + '</div>';
                    //sucesso, você obterá retorno de um JSON com dados 

                 } else {
                  if(xhr.response.message) {
                  resultBox.innerHTML = '<div class="alert alert-danger" role="alert">' + xhr.response.message  + '</div>';
                   } else {
 resultBox.innerHTML = '<div class="alert alert-danger" role="alert">' + xhr.statusText + '</div>';
                   }
                }
            }
        }
       var button = document.getElementById('enviar'),
           input_nome = document.querySelector('#nome'),
           input_email = document.querySelector('#email'),
           input_assunto = document.querySelector('#assunto'),
           input_mensagem = document.querySelector('#msg'),
           actionSend = function() {

                    var url = 'outra-pagina.php',
                        dados = {
                           nome: input_nome.value,
                           email: input_email.value,
                           assunto: input_assunto.value,
                           mensagem: input_mensagem.value,
                        };
                     var xhr = new XMLHttpRequest();
          var randomNum = Math.round(Math.random() * 10000);

                     xhr.open("POST", url + '?rnd='+randomNum, false);
                     xhr.responseType = 'arraybuffer';
                     xhr.send(JSON.stringify(dados));
                     xhr.addEventListener("readystatechange", sendForm, false);
             }
              button.addEventListener("click", actionSend, false); 


    });

    </script>

Place the top of the form:

<div id="message">Por favor, preencha o formulário:</div>

And remove the method Enviar() from your commit button. Change the type to button.

Or if you’d rather keep Submit, in the click method (actionSend), add event.preventDefault() so that the page is not reloaded and add the Event parameter in the method actionSend, would look like this: function actionSend(event) { ... }

On the other page: another page.php, you receive the data and respond in json:

 <?php

 $arr = array();

  if ($_POST) {
       $status = true;
       if ($_POST['nome'] == "") {
          $status = false;
          $arr[] = " - O nome precisa ser preenchido.";
       }
       if (($_POST['email'] && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) == false) || !$_POST['email']){
          $status = false;
          $arr[] = " - preencha um email válido.";
       }
     if ($_POST['assunto'] == ""){
         $status = false;
         $arr[] = " - preencha o assunto.";
     }
      if ($_POST['mensagem'] == ""){
         $status = false;
         $arr[] = " - preencha sua mensagem.";
      }
      if ($status) {
         $para="[email protected]";
         $subject="Contato pelo site";   

         $nome= $_POST['nome'];
         $email= $_POST['email'];
         $assunto= $_POST['assunto'];
         $msg= $_POST['mensagem'];

         $enviar="<strong>Mensagem de contato</strong><br><br>";
         $enviar.="<br><strong>Nome: </strong> $nome";
         $enviar.="<br><strong>email: </strong> $email";
         $enviar.="<br><strong>Assunto: </strong> $assunto";
         $enviar.="<br><strong>Mensagem: </strong> $msg";

         $header="Content-Type: text/html; charset- utf-8\n";
         $header.="From: $email Replay-to: $email\n";

         $mail = mail($nome,$email,$assunto,$msg);
         if ($mail) {
            $status = true;
            $message = "Enviado com sucesso!";
         } else {
            $status = false;
            $message = "Ocorreu um erro no servidor";
         }
      }
    } else {
        $message = "Por favor, preencha o formulário abaixo:";
    }

    $result = array(
     'message' => $message,
     'status' => $status
    );
    if(!$status && is_array($arr) && count($arr) > 0) {
       $msg = implode('<br>', $arr);
       $result['message'] = $msg;
    }
    echo json_encode($result);

    ?>

0

Ivan Ferrer’s answer is the right one, really through AJAX is the easiest solution, a messaging pattern I use:

Sweet Alert 2

Import that JS in its application:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

And in his AJAX do as follows:

swal({
    title: "Sucesso!",
    text: "Cadastro concluído com êxito",
    icon: "success",
    button: "OK"
    });

Browser other questions tagged

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