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

时间:2018-06-17 07:26:30

标签: javascript php

大家好,首先感谢您提供的任何帮助。我在这里搜索了数据库,并没有真正找到我的问题的解决方案。我很难让我的PHP脚本与我的HTML和javascript保持一致。我正在尝试在联系表单提交上创建一个弹出模式框。使用我当前的代码,我只是弹出失败框。任何人都可以看到我的编码错误在哪里?非常感谢。

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\n=============================\n";

    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\n";
        }
    }

    // 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("\n", $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.\n\n";

    $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)."\n";
    $email_message .= "Email Address: ".clean_string($email)."\n";
    $email_message .= "Message: ".clean_string($message)."\n";

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

die(json_encode($sent));

?>

1 个答案:

答案 0 :(得分:0)

错误在这里-

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

应该-

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