Success message after sending message by form

I want a message to appear on the same page after filling out the form and clicking on the "Send" button stating that the content has been sent successfully!

I will put my code, I appreciate the 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!");
}

?>
Author: Juliany Garcia, 2019-09-10

2 answers

Hello @ JulianyGarcia, welcome to StackOverflowPT, there are "n" ways to do this, using ajax, and making post directly on the page.

I would recommend you to study Javascript, which is a client-side language. I believe that using ajax , is a better way to send the data as it avoids reloading the page 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 email() function does not return an error.

I would recommend instead of using the mail function, use a library type PHPMailer, so you do not 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 contact.php and put a post condition:

<?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 a shipping method (some people like to use a library called jquery , but I prefer to use pure javascript, ES5 or ES6).

When submitting the form, you will continue on the page and synchronously send the data by ajax in json format, as soon as php dealing with this on the 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 Enviar() method from your Submit button. Change the type to button .

Or if you prefer to keep submit , in the click method (actionSend), append event.preventDefault() so that the page does not reload and append the event parameter in the actionSend method, it would look like this: function actionSend(event) { ... }

On the other page: other-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);

    ?>
 2
Author: Ivan Ferrer, 2019-09-11 12:00:43

The Answer form of Ivan Ferrer is the correct one, really through AJAX is the easiest solution, a pattern of messages that I use:

Sweet Alert 2

Import this JS into your application:

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

And in your AJAX do as follows:

swal({
    title: "Sucesso!",
    text: "Cadastro concluído com êxito",
    icon: "success",
    button: "OK"
    });
 0
Author: Fábio Santos, 2019-09-11 12:14:28