始终显示联系人表单中的问题成功消息

Issue with success message in a contact form always displayed

本文关键字:问题 成功 消息 表单 显示 联系人      更新时间:2023-11-04

我的联系人表单使用下面的代码。问题是,只要用户填写了联系人表单中的所有字段,并且引导验证程序检查通过,当他们单击"发送"时就会显示"成功"消息。这意味着,即使PHP文件被完全清空或不包含正确的smtp参数(因此可以肯定的是,消息永远不会被发送),成功消息仍然会显示。

如何调整JS代码,使其同时考虑PHP脚本的结果?

我不熟悉PHP和JS,但我想它应该是这样的:

  1. 当用户点击"发送"时,检查引导验证器的结果。

  2. 如果OK,从PHP脚本(成功或失败)中获取结果

  3. 如果引导验证器和PHP脚本都正常,则显示"成功"消息。如果没有,则显示"警报"消息。

感谢您的帮助

$(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:

$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);
?>

将成功消息的显示从提交处理程序移动到$.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');
  } 
  ...

您需要通过适当的回调来捕捉各种响应可能性。例如,如果请求/邮件发送失败,则应接收fail回调。如果邮件已发送,则可以触发success回调,如本文所述。

在您的代码中,替换:

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

像这样的东西:

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

以便实际触发错误回调。确保您的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');

试试这个