weixin_33696106 2017-04-19 03:46 采纳率: 0%
浏览 28

PHP / Ajax表单提交

I have designed a Sidebar Floating Form with PhP/Ajax which is working and sending submission to my targeted email. Here is the Link: http://logohour.com/form.html but when a visitor fill and submit the form successfully it routes him to another page for the confirmation.

This shouldn't be like this and must be stick to the homepage with popup Message as per my coding:

<div id="sendingMMessage" class="statusMessage">    <p>Sending your message. Please wait...</p>  </div>
  <div id="successMMessage" class="statusMessage">    <p>Thanks for sending your message! We'll get back to you shortly.</p>  </div>

Below you may find my Ajax & PHP for reference:

<?php

// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example@gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );

// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";

// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {

    $msgToSend = "Name: $Name
";
    $msgToSend .= "Email: $Email
";
    $msgToSend .= "Phone: $Phone
";
    $msgToSend .= "Sender Country: $Country
";
    $msgToSend .= "Sender Select: $Select
";
    $msgToSend .= "Message: $Message";

    $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
    $headers = "From: " . $Name . " <" . $Email . ">";
    $ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
  echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
  <head>
    <title>Thanks!</title>
  </head>
  <body>
  <?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
  <?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
  <p>Click your browser's Back button to return to the page.</p>
  </body>
</html>
<?php
}
?>

var messageDDelay = 2000; // How long to display status messages (in milliseconds)
    // Init the form once the document is ready
    $(init);
    // Initialize the form
    function init() {
      // Hide the form initially.
      // Make submitForm() the form's submit handler.
      // Position the form so it sits in the centre of the browser window.

      // When the "Send us an email" link is clicked:
      // 1. Fade the content out
      // 2. Display the form
      // 3. Move focus to the first field
      // 4. Prevent the link being followed
      $('a[href="#contact_form"]').click(function() {
        $('#content').fadeTo('slow', .2);
        $('#contact_form').fadeIn('slow', function() {
          $('#Name').focus();
        })
        return false;  });
      // When the "Cancel" button is clicked, close the form
      $('#cancel').click(function() {
        $('#contact_form').fadeOut();
        $('#content').fadeTo('slow', 1);
      });
      // When the "Escape" key is pressed, close the form
      $('#contact_form').keydown(function(event) {
        if (event.which == 27) {
          $('#contact_form').fadeOut();
          $('#content').fadeTo('slow', 1);}});}
    // Submit the form via Ajax
    function submitFForm() {
      var contact_form = $(this);
      // Are all the fields filled in?
      if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
        // No; display a warning message and return to the form
        $('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
        contact_form.fadeOut().delay(messageDDelay).fadeIn();
      } else {
        // Yes; submit the form to the PHP script via Ajax
        $('#sendingMMessage').fadeIn();
        contact_form.fadeOut();
        $.ajax({
          url: contact_form.attr('action') + "?ajax=true",
          type: contact_form.attr('method'),
          data: contact_form.serialize(),
          ssuccess: submitFFinished        });      }
      // Prevent the default form submission occurring
      return false;    }
    // Handle the Ajax response
    function submitFFinished(response) {
      response = $.trim(response);
      $('#sendingMMessage').fadeOut();
      if (response == "ssuccess") {
        // Form submitted ssuccessfully:
        // 1. Display the ssuccess message
        // 2. Clear the form fields
        // 3. Fade the content back in
        $('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
        $('#Name').val("");
        $('#Email').val("");
        $('#Phone').val("");
        $('#Country').val("");
        $('#Selct').val("");
        $('#Message').val("");
        $('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
      } else {
        // Form submission failed: Display the failure message,
        // then redisplay the form
        $('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
        $('#contact_form').delay(messageDDelay + 500).fadeIn();      }    }

</div>
  • 写回答

2条回答 默认 最新

  • 笑故挽风 2017-04-19 04:16
    关注

    First you have to avoid the normal form submission for this form and you can do this by using normal button instead of submit button.

    <input type="button" id="sendMMessage" name="sendMMessage" value="Submit">
    

    Execute a javascript ajax submit code onclick of sendMMessage id. and this will solve your problem.

    Updated answer :

    $( "#target" ).click(function() {
       // put your ajax form submit code here
      $.ajax({
               type: "POST",
               url: 'http://logohour.com/sidebar-form.php',
               data: $("#contact_form").serialize(), // serializes the form's elements.
               success: function(data)
               {
                   console.log(data); // show response from the php script.
               }
             });
    });
    

    If you are still unclear about this I will explain you more detail.

    thanks.

    评论

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”