You can accomplish this using jQuery and Ajax form.
First include jquery in your head element
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head>
Then specify your id form
<form id='mail_form' action="mail.php" method="POST">
Add a space somewhere with id = 'error'
<span id='error' style='color:red; font-weight:bold;'></span>
Correct the mail.php file as follows:
<?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); ?>
Then at the bottom of the page add
<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>
hunijkah
source share