doupuxuan5784 2018-06-17 07:26
浏览 78
已采纳

通过弹出模式成功或失败框联系表格

Hi everyone and first thanks in advance for any help that is given. I have searched the database here and not really found the solution to my problem. I'm having difficulty in getting my PHP script to align with my HTML and javascript. I'm trying to create a pop up modal box on contact form submission. With my current code i am just getting the fail box pop up. Can anyone see where my coding error is? Many Thanks again.

HTML -

<div class="col-md-7 contact-form">
                    <form action="contact.php" method="post" form id="contact-form">
                        <input type="text" name="Name" placeholder="Name" required>
                        <input type="email" class="email" name="Email" placeholder="Email" required>
                        <textarea placeholder="Message" name="Message" required></textarea>
                        <input type="submit" value="SUBMIT">
                    </form>
                </div>
                <div class="clearfix"> </div>   
            </div>
<div class="modal fade" id="thankyouModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header text-center">
          <h2 class="modal-title text-center" style="font-weight: 600; color: #393939;">THANKS</h2>
        </div>
        <div class="modal-body text-center" style="background-color: #fff;">
          <p style="font-weight: 600; color: #393939; font-size: 18px;">We will contact you as soon as possible!</p>
        </div>
        <div class="modal-footer" style="background-color: #fff; border-top: 0px solid #fff;">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->

  <div id="fail-modal" class="modal fade" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Ace Motorcycles</h4>
        </div>
        <div class="modal-body">
          <p>Sorry something went wrong in sending your message. Please try again</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

  <script src="js/jquery-2.2.3.min.js"></script>
  <script src="js/bootstrap.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $("#contact-form").on("submit", function(event) {
        event.preventDefault();

        request = $.ajax({
          url: "process.php",
          type: "post",
          data: $(this).serialize(),
          dataType:"json"
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus){
          if (response == true ) {
            console.log('true');
            $('#thankyouModal').modal('show');
          } else {
            console.log('false');
            $('#fail-modal').modal('show');
          }
        });

        // Callback handler that will be called on failure
        request.fail(function (textStatus, errorThrown){
          // Log the error to the console
          console.error(
            "The following error occurred: "+ textStatus, errorThrown
          );
        });
      });
    });
  </script>

contact.php -

/*
 *  CONFIGURE EVERYTHING HERE
 */

// an email address that will be in the From field of the email.
$from = 'Website Enquiry';

// an email address that will receive the email with the output of the form
$sendTo = 'timmy2872@gmail.com';

// subject of the email
$subject = 'New message from contact form';

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('Name' => 'Name', 'Email' => 'Email', 'Message' => 'Message'); 

// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted. Thank you, we will get back to you very soon!';

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';

/*
 *  LET'S DO THE SENDING
 */

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');

    $emailText = "You have a new message from your contact form
=============================
";

    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email 
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value
";
        }
    }

    // All the neccessary headers for the email.
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
        'From: ' . $from,
        'Reply-To: ' . $from,
        'Return-Path: ' . $from,
    );

    // Send email
    mail($sendTo, $subject, $emailText, implode("
", $headers));

    $responseArray = array('type' => 'success', 'message' => $okMessage); 
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage); 
}


// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];
}

process.php -

header('Content-Type: application/json');

$sent = false;
if(isset($_POST['submit'])) {     
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "timmy2872@gmail.com";

    // EDIT THE 2 LINES BELOW AS REQUIRED
    $sender = $_POST['Email'];

    $name = $_POST['Name']; // required
    $email = $_POST['Email']; // required
    $message = $_POST['Message']; //required

    $email_message = "Below is the message.

";

    $email_subject = "Contact details - $name";

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }

    $email_message .= "Name: ".clean_string($name)."
";
    $email_message .= "Email Address: ".clean_string($email)."
";
    $email_message .= "Message: ".clean_string($message)."
";

    // create email headers
    $headers = 'From:'.$sender."
".
    'Reply-To: '.$email."
" .
    'X-Mailer: PHP/' . phpversion();
    $sent= @mail($email_to, $email_subject, $email_message, $headers); 
}

die(json_encode($sent));

?>
  • 写回答

1条回答 默认 最新

  • dpsr1670 2019-08-19 14:56
    关注

    Error was here -

         $("#contact-form").on("submit", function(event) {
        event.preventDefault();
    

    Should of been -

         $("#contact").on("submit", function(event) {
         event.preventDefault();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形