Home » Php » javascript – Simple contact form success popup on same page

javascript – Simple contact form success popup on same page

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a simple contact form with contact.html and mail.php page. I want a success popup on the same page when click on submit button. Perhaps needs to use ajax. If anyone could help me. Thanks a lot.

mail.php-

<?php
 $name = $_POST['name'];
 $email = $_POST['email'];
 $recipient = "[email protected]";
 $subject = "Contact Form";
 $mailheader = "From: $email \r\n";
 mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
 echo "Thank You!" . " -" . "<a href='form.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>

contact.html-

<form action="mail.php" method="post" id="custom-form">
 <input type="text" placeholder="Name" name="name" required="">
 <input type="text" placeholder="Email" name="email" required="">
 <button class="btn" type="submit" value="send">Submit</button>
</form>
How to&Answers:

in contact.html

<form action="mail.php" method="post" id="custom-form">
  <input type="text" placeholder="Name" name="name" required="">
  <input type="text" placeholder="Email" name="email" required="">
  <button class="btn" type="submit" value="send">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title processing">Loading...</h4>
      </div>
     <div class="modal-body">
       <p class="repons2"></p>
     </div>
   </div>
</div></div>
<script>
  $('#custom-form').submit(function (e) {
    e.preventDefault();
    var form_data = new FormData($(this)[0]);
    var fa = $(this);
    $('#myModal').modal('show');
    $.ajax({
      url: fa.attr('action'),
      type: 'post',
      data: form_data,
      dataType: 'json',
      success: function (response) {
        $('.repons2').html(response.messages)
        $('.processing').html(response.status)
      }
   });
 });
</script>

in mail.php

<?php
      $name = $_POST['name'];
      $email = $_POST['email'];
      $recipient = "[email protected]";
      $subject = "Contact Form";
      $mailheader = "From: $email \r\n";
      if(mail($recipient, $subject, $formcontent, $mailheader)){
          $status="success send";
          $message= "Thank You!" . " -" . "<a href='form.html' style='text- decoration:none;color:#ff0099;'> Return Home</a>";
      }else{
         $status="fail send";
         $message="sending error";
      }
      $data=[
             "status"=>$status,
             "messages"=>$message
           ]
          echo json_encode($data);
?>

don’t forget to load the jquery for ajax to work