drwurqczo39355510
2016-04-02 07:19
浏览 40

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

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.

How can I adapt the JS code so that it also takes into consideration the results of the PHP script?

I'm not familiar with PHP and JS but I guess it should be something like this:

  1. When user click "send", check bootstrapvalidator results.

  2. If OK, obtain result from PHP script (success or failure)

  3. If both bootstrapvalidator and PHP script are OK, display "success" message. 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:

$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条回答 默认 最新

  • duandiaoqian5795 2016-04-02 07:28
    已采纳
      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

    打赏 评论
  • douyi5822 2016-04-02 07:26

    Move the displaying of the success message from the submit handler into the callback on your $.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');
      } 
      ...
    
    打赏 评论
  • duangelin7513 2016-04-02 07:33

    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. If the mail was sent, the success callback can be triggered, as documented here.

    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.

    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);
    }
    
    打赏 评论

相关推荐 更多相似问题