Замена формы HTML с сообщением об успешности после отправки, форма отправляет почту с использованием отдельного php-файла

У меня есть html-контактная форма, которая встроена в index.html, а затем у меня есть файл mail.php, который отправляет почту, а также использует Javascript. Когда я заполняю форму и отправлю, я закодировал ее, чтобы отправить почту, а затем она появляется с сообщением об успешном сообщении и затем перенаправляется обратно в index.html.

Я бы хотел, чтобы форма была заменена сообщением об успешном завершении, чтобы избежать обновления страницы, а также во избежание появления всплывающего окна.

form from index.html:

<form action="mail.php" method="POST"> <div class="row uniform"> <div class="6u 12u$(xsmall)"> <input type="text" name="name" id="name" value="" placeholder="Name" /> </div> <div class="6u$ 12u$(xsmall)"> <input type="email" name="email" id="email" value="" placeholder="Email" /> </div> <div class="12u$"> <!--<div class="select-wrapper"> </div>--> </div> <div class="12u$"> <textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea> </div> <center><div class="g-recaptcha" data-sitekey=""></div></center> <div class="12u$"> <ul class="actions"> <li><input type="submit" value="Send Message" class="special" /></li> <li><input type="reset" value="Reset" /></li> </ul> </div> </div> </form> 

php-файл, адрес электронной почты и токен recaptcha удалены по понятным причинам:

 <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha; { if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { echo '<script language="javascript">'; echo 'alert("Please check the Captcha")'; echo '</script>'; exit; } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { echo '<h2>Please do not try and spam here.</h2>'; }else { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo '<script language="javascript">'; echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; echo 'window.location.href="index.html";'; echo '</script>'; } } ?> , <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha; { if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { echo '<script language="javascript">'; echo 'alert("Please check the Captcha")'; echo '</script>'; exit; } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { echo '<h2>Please do not try and spam here.</h2>'; }else { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo '<script language="javascript">'; echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; echo 'window.location.href="index.html";'; echo '</script>'; } } ?> , <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha; { if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { echo '<script language="javascript">'; echo 'alert("Please check the Captcha")'; echo '</script>'; exit; } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { echo '<h2>Please do not try and spam here.</h2>'; }else { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo '<script language="javascript">'; echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; echo 'window.location.href="index.html";'; echo '</script>'; } } ?> , <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha; { if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { echo '<script language="javascript">'; echo 'alert("Please check the Captcha")'; echo '</script>'; exit; } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { echo '<h2>Please do not try and spam here.</h2>'; }else { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo '<script language="javascript">'; echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; echo 'window.location.href="index.html";'; echo '</script>'; } } ?> , <?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha; { if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { echo '<script language="javascript">'; echo 'alert("Please check the Captcha")'; echo '</script>'; exit; } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { echo '<h2>Please do not try and spam here.</h2>'; }else { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); echo '<script language="javascript">'; echo 'alert("Your Message successfully sent, we will get back to you ASAP.");'; echo 'window.location.href="index.html";'; echo '</script>'; } } ?> 

Это тема, на которую я действительно посмотрел:

Очистить форму после отправки и успешного сообщения

Лучший способ сделать все ваши вещи – использовать ajax. Включите jquery в свой html.

Поместите свою форму внутри оболочки div

 <div class="something"> <!-- your form here --> </div> 

Отправьте форму через ajax, вместо того, чтобы использовать базовую форму представления

 //"idform" is the id of the form $("#idForm").submit(function() { var url = "path/to/your/script.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, // serialize your form's elements. data: $("#idForm").serialize(), success: function(data) { // "something" is the class of your form wrapper $('.something').html(data); } }); // avoid to execute the actual submit of the form. return false; }); - //"idform" is the id of the form $("#idForm").submit(function() { var url = "path/to/your/script.php"; // the script where you handle the form input. $.ajax({ type: "POST", url: url, // serialize your form's elements. data: $("#idForm").serialize(), success: function(data) { // "something" is the class of your form wrapper $('.something').html(data); } }); // avoid to execute the actual submit of the form. return false; }); 

И последнее, что вам нужно изменить, – это ваш php-код

сохранить только одно эхо для успеха

 echo "Your Message successfully sent, we will get back to you ASAP."; 

Прежде всего, вы должны использовать вызов AJAX для отправки формы. Если вы настаиваете на использовании чистого JS, сценарий будет выглядеть так (написанный за 5 секунд – возможно, потребуется некоторая настройка):

 <script> document.forms['yourForm'].onsubmit = function(form) { // you have to add 'name' attribute to the form and replace 'yourForm' with it var data = ... //here you have to get all the values from form elements and store them in data object. to make less changes to the script use the elements' names as object names if (window.XMLHttpRequest) { var xhReq = new XMLHttpRequest(); } else { var xhReq = new ActiveXObject("Microsoft.XMLHTTP"); } var method= 'POST') var async = false; //you can actually set true here, it doesn't matter much in this case var url = 'mail.php'; xhReq.open(method, url, async); xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhReq.send(data); document.getElementById("form's parent's ID goes here").innerHTML = "new content" return false; } </script> 

Затем вам нужно удалить все эхо из файла php, так как он не будет показан в любом случае. Вы также можете добавить еще некоторые сложности для этого скрипта, например, проверить правильность работы почтовой функции (путем возврата чего-либо в файл php и проверки ответа AJAX в JS) или для обнаружения ошибок captcha. Это также было бы очень легко достичь в jQuery, если вы захотите пойти по этой дороге.

Вы можете выполнить это, используя форму jQuery и Ajax submit.

Во-первых, включить jquery в свой элемент head

 <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> 

Затем дайте вашей форме идентификатор

 <form id='mail_form' action="mail.php" method="POST"> 

Добавьте пробел где-то с id = 'error'

 <span id='error' style='color:red; font-weight:bold;'></span> 

Отрегулируйте mail.php следующим образом:

 <?php $success = true; $errors = array(); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha = false; if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { $success = false; array_push($errors, "Please check the captcha"); } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { $success = false; array_push($errors, "Please do not try and spam here."); } if ($success) { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); } $output_array = array("success" => $success, "errors" => $errors); echo json_encode($output_array); ?> , <?php $success = true; $errors = array(); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha = false; if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { $success = false; array_push($errors, "Please check the captcha"); } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { $success = false; array_push($errors, "Please do not try and spam here."); } if ($success) { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); } $output_array = array("success" => $success, "errors" => $errors); echo json_encode($output_array); ?> , <?php $success = true; $errors = array(); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha = false; if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { $success = false; array_push($errors, "Please check the captcha"); } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { $success = false; array_push($errors, "Please do not try and spam here."); } if ($success) { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); } $output_array = array("success" => $success, "errors" => $errors); echo json_encode($output_array); ?> , <?php $success = true; $errors = array(); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $formcontent = "From: $name \n email: $email \n Message: $message"; $recipient = 'email address here'; $subject = 'Message from Website'; $mailheader = "From: $email \r\n"; $captcha = false; if(isset($_POST['g-recaptcha-response'])) { $captcha=$_POST['g-recaptcha-response']; } if(!$captcha) { $success = false; array_push($errors, "Please check the captcha"); } $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); if($response.success==false) { $success = false; array_push($errors, "Please do not try and spam here."); } if ($success) { mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); } $output_array = array("success" => $success, "errors" => $errors); echo json_encode($output_array); ?> 

Затем в нижней части страницы добавьте

 <script> $('#mail_form').on('submit', function(){ var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to mail.php. Try doing alert(dataIn); to see what it holds. $.post( "./mail.php", dataIn ) .done(function( dataOut ) { //dataOut holds the response from mail.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery. var myArray = JSON.parse(dataOut ); if (myArray['success'] == true) //Check if it was successfull. { $("#mail_form").html("Congrats! We just e-mailed you!"); } else //there were errors { $('#error').html(""); //Clear error span $.each(myArray['errors'], function(i){ $('#error').append(myArray['errors'][i] + "<br>"); } }); return false; //Make sure you do this or it will submit the form and redirect }); </script>