Bruno Santos
Bruno Santos

Reputation: 13

SweetAlert + Form HTML + PHP

I do this long years ago, but now, I don't remember and I can't put this working...

So, I have a form with action to another file.php, to send an email, and I want to put a sweet alert to tell people, okay your message has been sent...

Check the code in CONTACT.PHP

        <link href="sweet/style.css" type="text/css" rel="stylesheet">
    <link href="sweet/sweetalert.css" type="text/css" rel="stylesheet">
    <script src="sweet/jquery-3.4.1.min.js" type="text/javascript"></script>
    <script src="sweet/sweetalert.min.js" type="text/javascript"></script>

    <script type='text/javascript'>
    $( document ).ready(function() {



        // Show image
        $("#but3").click(function(){
            var message = $("#message").val();
            var title = $("#title").val();
            if(message == "Welcome"){
                message  = "Welcome";
            }
            if(title == "Welcome"){
                title = "Welcome";
            }
            swal({
            title: title,
            text: message,
            imageUrl: "logo.png"
            });
        });

        // Timer
        $("#but4").click(function(){
            var message = $("#message").val();
            var title = $("#title").val();
            if(message == ""){
                message  = "Your message";
            }
            if(title == ""){
                title = "Your message";
            }
            message += "(close after 2 seconds)";
            swal({
                title: title,
                text: message,
                timer: 2000,
                showConfirmButton: false
            });
        });
    });
    </script>

    <!-- main-container -->
    <div class="container main-container">
        <div class="col-md-6">
            <form action="envia.php" name="envia" id="envia" method="post">
                <div class="row">
                    <div class="col-md-6">
                        <div class="input-contact">
                            <input type="text" name="nome" id="nome" required>
                            <span>Nome</span>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="input-contact">
                            <input type="text" id="email" name="email" required>
                            <span>Email</span>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="input-contact">
                            <input type="text" name="assunto" id="assunto" required>
                            <span>Assunto</span>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="textarea-contact">
                            <textarea name="menssagem" id="mensagem" required></textarea>
                            <span>Mensagem</span>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <input type="submit" name="enviar"  value="enviar" class="btn btn-box">
                    </div>
                </div>
            </form>

            <table>
              <tr><td> THIS SMALL FORM ITS JUST FOR SHOW SWEET ALERT </TD></TR>
                <tr>
                    <td>Title</td>
                    <td><input type='text' value='Title text' id='title'></td>
                </tr>
                <tr>
                    <td>Message</td>
                    <td><input type='text' value='Your message' id='message'></td>
                </tr>
                <tr>
                    <td colspan='2'>
                    <input type='button' value='Alert with image' id='but4'>&nbsp;
                    </td>
                </tr>
            </table>


        </div>

--

        <!-- main-container -->
        <div class="container main-container">
            <div class="col-md-6">
                <form action="envia.php" name="envia" id="envia" method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="input-contact">
                                <input type="text" name="nome" id="nome" required>
                                <span>Nome</span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="input-contact">
                                <input type="text" id="email" name="email" required>
                                <span>Email</span>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="input-contact">
                                <input type="text" name="assunto" id="assunto" required>
                                <span>Assunto</span>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="textarea-contact">
                                <textarea name="menssagem" id="mensagem" required></textarea>
                                <span>Mensagem</span>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <input type="submit" name="enviar"  value="enviar" class="btn btn-box">
                        </div>
                    </div>
                </form>

                <table>
                  <tr><td> THIS SMALL FORM ITS JUST FOR SHOW SWEET ALERT </TD></TR>
                    <tr>
                        <td>Title</td>
                        <td><input type='text' value='Title text' id='title'></td>
                    </tr>
                    <tr>
                        <td>Message</td>
                        <td><input type='text' value='Your message' id='message'></td>
                    </tr>
                    <tr>
                        <td colspan='2'>
                        <input type='button' value='Alert with image' id='but4'>&nbsp;
                        </td>
                    </tr>
                </table>


            </div>

THE FILE ENVIA.PHP

$nomeremetente = $_POST['nome'];
$emailremetente = trim($_POST['email']);
$emaildestinatario = '[email protected]';// Digite seu e-mail aqui, lembrando que o e-mail deve estar em seu servidor web
$assunto = $_POST['assunto'];
$mensagem = $_POST['mensagem'];

/* Montando a mensagem a ser enviada no corpo do e-mail. */
$mensagemHTML = '
<strong>Formulário de Contato</strong>
<p><b>Nome:</b> '.$nomeremetente.' <p>
<b>E-Mail:</b> '.$emailremetente.' <p>
<b>Assunto:</b> '.$assunto.' <p>
<b>Mensagem:</b> '.$mensagem.'</p>
<hr>';

// O remetente deve ser um e-mail do seu domínio conforme determina a RFC 822.
// O return-path deve ser ser o mesmo e-mail do remetente.
$headers = "MIME-Version: 1.1\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: $emailremetente\r\n";
// remetente
$headers .= "Return-Path: $emaildestinatario \r\n";
// return-path
$envio = mail($emaildestinatario, $assunto, $mensagemHTML, $headers);
if($envio)
echo "<script>location.href='contact.php'</script>";// Página que será redirecionada

I have tried so many ways, and I just reset everything and now I don't know what to do.........

Upvotes: 0

Views: 3228

Answers (1)

Souhailhimself
Souhailhimself

Reputation: 231

Edited to the full code fix

contact.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Box personal portfolio Template</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <link href="ionicons/css/ionicons.min.css" rel="stylesheet" />
    <link rel="icon" href="img/fav.png" type="image/x-icon" />
    <!-- main css -->
    <link href="css/style.css" rel="stylesheet" />
    <!-- Sweetalert -->
    <!-- <link href="sweet/style.css" type="text/css" rel="stylesheet" /> -->
    <link href="sweet/sweetalert.css" type="text/css" rel="stylesheet" />
    <script src="sweet/sweetalert.min.js" type="text/javascript"></script>
    <!-- modernizr -->
    <script src="js/modernizr.js"></script>
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <!-- Preloader -->
    <div id="preloader">
      <div class="pre-container">
        <div class="spinner">
          <div class="double-bounce1"></div>
          <div class="double-bounce2"></div>
        </div>
      </div>
    </div>
    <!-- end Preloader -->
    <div class="container-fluid">
      <!-- box-header -->
      <header class="box-header">
        <div class="box-logo">
          <a href="index.html"
            ><img src="img/logo.png" width="80" alt="Logo"
          /></a>
        </div>
        <!-- box-nav -->
        <a class="box-primary-nav-trigger" href="#0">
          <span class="box-menu-text">Menu</span
          ><span class="box-menu-icon"></span>
        </a>
        <!-- box-primary-nav-trigger -->
      </header>
      <!-- end box-header -->
      <!-- nav -->
      <nav>
        <ul class="box-primary-nav">
          <li class="box-label">About me</li>
          <li><a href="index.html">Intro</a></li>
          <li><a href="about.html">About me</a></li>
          <li><a href="services.html">services</a></li>
          <li><a href="portfolio.html">portfolio</a></li>
          <li>
            <a href="contact.html">contact me</a>
            <i class="ion-ios-circle-filled color"></i>
          </li>
          <li class="box-label">Follow me</li>
          <li class="box-social">
            <a href="#0"><i class="ion-social-facebook"></i></a>
          </li>
          <li class="box-social">
            <a href="#0"><i class="ion-social-instagram-outline"></i></a>
          </li>
          <li class="box-social">
            <a href="#0"><i class="ion-social-twitter"></i></a>
          </li>
          <li class="box-social">
            <a href="#0"><i class="ion-social-dribbble"></i></a>
          </li>
        </ul>
      </nav>
      <!-- end nav -->
    </div>
    <!-- top bar -->
    <div class="top-bar">
      <h1>contact Me</h1>
      <p><a href="#">Home</a> / Contact Me</p>
    </div>
    <!-- end top bar -->
    <!-- main-container -->
    <div class="container main-container">
      <div class="col-md-6">
        <form name="envia" action="#" id="envia">
          <div class="row">
            <div class="col-md-6">
              <div class="input-contact">
                <input type="text" name="nome" id="nome" required />
                <span>Nome</span>
              </div>
            </div>
            <div class="col-md-6">
              <div class="input-contact">
                <input type="text" id="email" name="email" required />
                <span>Email</span>
              </div>
            </div>
            <div class="col-md-12">
              <div class="input-contact">
                <input type="text" name="assunto" id="assunto" required />
                <span>Assunto</span>
              </div>
            </div>
            <div class="col-md-12">
              <div class="textarea-contact">
                <textarea name="menssagem" id="mensagem" required></textarea>
                <span>Mensagem</span>
              </div>
            </div>
            <div class="col-md-12">
              <input
                id="submit"
                type="submit"
                name="enviar"
                value="enviar"
                class="btn btn-box"
              />
            </div>
          </div>
        </form>
      </div>
      <div class="col-md-6">
        <h3 class="text-uppercase">Entre em contacto</h3>
        <h5>Pedidos orçamento e esclarecimento de dúvidas.</h5>
        <div class="h-30"></div>
        <p>
          <br />Poderá usar este formulário para esclarecimento de dúvidas ou
          pedido de orçamento, para pedidos de orçamento deverá indicar o mais
          claro possivel o que pretende.
        </p>
        <div class="contact-info">
          <p><i class="ion-android-call"></i>911729199</p>
          <p><i class="ion-ios-email"></i>[email protected]</p>
        </div>
      </div>
    </div>
    <!-- end main-container -->
    <!-- footer -->
    <footer>
      <div class="container-fluid">
        <p class="copyright">© Box Portfolio 2016</p>
      </div>
    </footer>
    <!-- end footer -->
    <!-- back to top -->
    <a href="#0" class="cd-top"><i class="ion-android-arrow-up"></i></a>
    <!-- end back to top -->
    <!-- jQuery -->
    <script src="js/jquery-2.1.1.js"></script>
    <!--  plugins -->
    <script src="js/bootstrap.min.js"></script>
    <script src="js/menu.js"></script>
    <script src="js/animated-headline.js"></script>
    <script src="js/isotope.pkgd.min.js"></script>
    <!--  custom script -->
    <script src="js/custom.js"></script>
    <script>
      // This will prevent the default button action and the page won't refresh
      document.querySelector("#submit").addEventListener(
        "click",
        function (event) {
          process();
        },
        false
      );
      // This will make a post request to your php file
      function process() {
        // Getting the inputs
        var message = document.getElementById("mensagem").value;
        var email = document.getElementById("email").value;
        var subject = document.getElementById("assunto").value;
        var name = document.getElementById("nome").value;
        // Some data validation to see if the user have filled the required fields
        if (message && email && subject && name) {
          event.preventDefault();
          // Setting the AJAX request handler
          var xmlhttp = new XMLHttpRequest();
          // Waiting for a response
          xmlhttp.onreadystatechange = function () {
            // If the response is 200 aka "OK"
            if (this.readyState == 4 && this.status == 200) {
              // Show your success alert here
              swal({
                title: "Message Sent!",
                text: "Thank you for contacting us.",
                timer: 2000,
                showConfirmButton: false,
              });
              document.getElementById("envia").reset();
              return;
            }
          };
          // Setting the request type and data to be sent
          xmlhttp.open("POST", "envia.php", true);
          xmlhttp.setRequestHeader(
            "Content-type",
            "application/x-www-form-urlencoded"
          );
          xmlhttp.send(
            "nome=" +
              name +
              "&email=" +
              email +
              "&assunto=" +
              subject +
              "&mensagem=" +
              message
          );
        } else {
          // Alert the user to fill the required fields
          console.log("please fill all required fields");
          return;
        }
      }
    </script>
  </body>
</html>

envia.php

<?php
$nomeremetente     = $_POST['nome'];
$emailremetente  = $_POST['email'];
$emaildestinatario  = '[email protected]';
$assunto = $_POST['assunto'];
$mensagem = $_POST['mensagem'];
$content = '<strong>Formulário de Contato</strong><p><b>Nome:</b> ' . $nomeremetente . ' <p><b>E-Mail:</b> ' . $emailremetente . ' <p><b>Assunto:</b> ' . $assunto . ' <p><b>Mensagem:</b> ' . $mensagem . '</p><hr>';
$headers = array(
    'From' => $emailremetente,
    'Reply-To' => $emaildestinatario,
    'MIME-Version' => '1.1',
    'Content-type' => 'text/html;charset=UTF-8',
    'X-Mailer' => 'PHP/' . phpversion()
);
if (isset($nomeremetente) && isset($emailremetente) && isset($emaildestinatario) && isset($assunto) && isset($mensagem) && isset($content)) {
    mail($emaildestinatario, $assunto, $content, $headers);
    echo "SUCCESS";
    http_response_code(200);
} else {
    echo "FAILED";
    http_response_code(404);
}

Take note that I have added already the sweet alert you can go ahead and customize the message to display after email success

NB: Don't forget to change the email that you're going to receive email on to one on your domain or the emails would end up not getting sent or in your spam

Upvotes: 1

Related Questions