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

时间:2016-04-02 07:19:12

标签: javascript php twitter-bootstrap

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

如何调整JS代码以便它还考虑PHP脚本的结果?

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

  1. 当用户点击"发送"时,请检查bootstrapvalidator结果。

  2. 如果正常,请从PHP脚本获取结果(成功或失败)

  3. 如果bootstrapvalidator和PHP脚本都正常,则显示" success"信息。如果没有,请显示" alert"消息。

  4. 感谢您的帮助

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

在您的代码中,替换:

$.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);
}

答案 2 :(得分:0)

  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');

试试这个