简体   繁体   English

总是显示联系表单中的成功消息问题

[英]Issue with success message in a contact form always displayed

I'm using the code below for my contact form. 我在联系表格中使用以下代码。 The issue is that as long as the users fill in all the fields in the contact form and bootstrap validator checks are passed, the "success" message is displayed when they click "send". 问题是,只要用户填写联系表单中的所有字段并通过引导验证程序检查,当他们单击“发送”时,就会显示“成功”消息。 It means that even when the PHP file is completely emptied or does not contain the correct smtp parameters (so for sure the message will never be sent), the success message is still displayed. 这意味着即使PHP文件被完全清空或不包含正确的smtp参数(因此,也将确保永远不会发送消息),仍然会显示成功消息。

How can I adapt the JS code so that it also takes into consideration the results of the PHP script? 如何修改JS代码,使其也考虑PHP脚本的结果?

I'm not familiar with PHP and JS but I guess it should be something like this: 我不熟悉PHP和JS,但我想应该是这样的:

  1. When user click "send", check bootstrapvalidator results. 用户单击“发送”时,检查bootstrapvalidator结果。

  2. If OK, obtain result from PHP script (success or failure) 如果可以,请从PHP脚本获取结果(成功或失败)

  3. If both bootstrapvalidator and PHP script are OK, display "success" message. 如果bootstrapvalidator和PHP脚本均正常,则显示“成功”消息。 If not, display "alert" message. 如果不是,则显示“警告”消息。

Thanks for your help 谢谢你的帮助

$(document).ready(function() {
    $('#contact_form').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
      submitHandler: function(validator, form, submitButton) {
        $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...
                $('#contact_form').data('bootstrapValidator').resetForm();
                $('button[name="submit"]').hide();

            var bv = form.data('bootstrapValidator');
            // Use Ajax to submit form data
            $.post(form.attr('action'), form.serialize(), function(result) {
                console.log(result);
            }, 'json');
      },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            message: {
                validators: {
                      stringLength: {
                        min: 10,
                        max: 200,
                        message:'Please enter at least 10 characters and no more than 200'
                    },
                    notEmpty: {
                        message: 'Please supply a description of your project'
                    }
                    }
                }
            }
        })

});

PHP: PHP:

$mail->Subject = "New message from " . $_POST['first_name'] . $_POST['last_name'];
$mail->Body =  $_POST['message']."<br><br>From page: ". str_replace("http://", "", $_SERVER['HTTP_REFERER']) . "<br>" . $_SERVER ['HTTP_USER_AGENT'] ;

$response = array();
if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}

/* send content type header */
header('Content-Type: application/json');

/* send response as json */
echo json_encode($response);

?>

Move the displaying of the success message from the submit handler into the callback on your $.post . 将成功消息的显示从提交处理程序移到$.post上的回调中。

...
submitHandler: function(validator, form, submitButton)  {
    $('#contact_form').data('bootstrapValidator').resetForm();
    $('button[name="submit"]').hide();
    var bv = form.data('bootstrapValidator'); 

    // Use Ajax to submit form data
    $.post(form.attr('action'), form.serialize(), function(result 
    { 
        // Check for valid response from your phone script 
        $('#success_message').slideDown({ opacity: "show" }, "slow");
        console.log(result);
        }, 'json');
  } 
  ...

You'll want to catch the various response possibilities with proper callbacks. 您将需要使用适当的回调来捕获各种响应可能性。 For example, if the request/mailing failed, the fail callback should be received. 例如,如果请求/邮件失败,则应接收fail回调。 If the mail was sent, the success callback can be triggered, as documented here . 如果发送了邮件,则可以触发success回调, 如此处所述

In your code, replace: 在您的代码中,替换为:

$.post(form.attr('action'), form.serialize(), function(result) {
    console.log(result);
}, 'json');

With something like this: 用这样的东西:

$.post(form.attr('action'), form.serialize(), function(result) {
    console.log(result);
}, 'json').done(function() {
    alert( "success" );
}).fail(function() {
    alert( "error" );
});

In order to actually trigger the error callback. 为了实际触发错误回调。 Make sure your PHP script doesn't return a 200 OK status, but something like a 400 Bad Request response. 确保您的PHP脚本未返回200 OK状态,而是返回400 Bad Request响应。

if(!$mail->send()) {
  $response = array('message'=>"Mailer Error: " . $mail->ErrorInfo, 'status'=> 0);
  header("HTTP/1.0 400 Bad Request");
} else {
  $response = array('message'=>"Message has been sent successfully", 'status'=> 1);
}
  submitHandler: function (validator, form, submitButton) {
          $('button[name="submit"]').hide();

          var bv = form.data('bootstrapValidator');
          // Use Ajax to submit form data
          $.post(form.attr('action'), form.serialize(), function (result) {
              if (result.status == 1) {
                  $('#success_message').slideDown({
                      opacity: "show"
                  }, "slow")
                  $('#contact_form').data('bootstrapValidator').resetForm();
              } else {
                  //show the error message 
              }
          }, 'json');

Try this 尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM