Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing HTML form with success message after submit, form sends mail using separate php file

I have an html contact form which is built into index.html, and then I have a mail.php file that sends a mail and also uses some Javascript. When I fill in form and submit, I have coded it to send the mail and then it pops up with a success message box and then redirects back to index.html.

What I would like is for the form to be replaced with the success message, to avoid a page refresh and also to avoid the popup message box.

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 file, email address and recaptcha token removed for obvious reasons:

<?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>';
  }
} ?>

This is a topic that I have actually looked at:

Clear form after submit and success message

like image 414
Troy Avatar asked Oct 13 '15 07:10

Troy


2 Answers

Best way to do all your stuff is to use ajax. Include jquery in your html.

Put your form inside a wrapper div

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

Submit your form through ajax, instead of using basic form submission

//"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;
});

And last thing you need to change is in your php code

keep only one echo for success

echo "Your Message successfully sent, we will get back to you ASAP.";
like image 197
Sumit Pandey Avatar answered Oct 19 '22 18:10

Sumit Pandey


First of all you should use AJAX call to submit the form. If you insist on using pure JS the script would look like this (written in 5 seconds - probably needs some adjusting):

<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>

Than you have to remove all echos from php file as it wouldn't be shown anyway. You can also add some more sophistication to this script e.g. check if the mail function worked correctly (by returning something in php file and checking the AJAX response in JS) or to catch the captcha errors. It would also be extremely easier to achieve in jQuery if you're willing to go down that road.

like image 1
kacper3w Avatar answered Oct 19 '22 18:10

kacper3w