发送联系表单而不离开页面和bootstrapValidator

时间:2016-03-28 12:34:41

标签: javascript php ajax twitter-bootstrap phpmailer

我使用codepen中的this code作为我的联系表单。

我遇到的问题是,一旦您点击了"发送"按钮,您将联系表单所在的页面发送到sendmessage.php。

我希望看到的是表单的正常行为:当您点击"发送" (并且消息传输成功),您保持在同一页面上,"发送"按钮消失,取而代之的是"成功"消息,无需离开或重新加载页面,表格放在哪里..

知道当前代码的问题是什么吗?您可以测试我的实例[{3}}

非常感谢,

HTML:

<form class="well form-horizontal" action="../sendmessage.php" method="post"  id="contact_form">

使用Javascript:

  $(document).ready(function() {
    $('#contact_form').bootstrapValidator({
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'Please supply your email address'
                    },
                    emailAddress: {
                        message: 'Please supply a valid email address'
                    }
                }
            },            
            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'
                    }
                    }
                }
            }
        })
        .on('success.form.bv', function(e) {
            $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ...

                $('#contact_form').data('bootstrapValidator').resetForm();

            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {
                console.log(result);
            }, 'json');
        });
});

sendmessage.php的内容:

<?php

require 'PHPMailer/PHPMailerAutoload.php';

$mail = new PHPMailer;
$mail->CharSet = 'utf-8';

//Enable SMTP debugging. 
$mail->SMTPDebug = false;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.elasticemail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "xyz";                 
$mail->Password = "xyz";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 2525;                                   

$mail->From = $_POST['email'];
$mail->FromName = $_POST['first_name'];

$mail->addAddress("xyz@gmail.com");
//CC and BCC
$mail->addCC("xyz@outlook.com");
$mail->addBCC("");

$mail->isHTML(true);

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

?>

2 个答案:

答案 0 :(得分:1)

您是否尝试过在提交事件中返回false?

$('#contact_form').on('submit', function(event) {
  event.preventDefault();
  return false;
});

答案 1 :(得分:0)

您需要将bootstrapvalidator.min.js文件0.4.5更新为最新文件

https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js

我创建了一个小提琴https://jsfiddle.net/nwk9dLrn/8/ plz检查,但我没有添加它的ajax.php文件,但你可以在控制台中看到它。 更新bootstrapvalidator文件时,这将有效。

$('#contact_form').bootstrapValidator({
        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please supply your first name'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'Please supply your email address'
                    },
                    emailAddress: {
                        message: 'Please supply a valid email address'
                    }
                }
            },            
            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'
                    }
                    }
                }
            }
        })
        .on('success.form.bv', function(e) {
            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {                
                $("#success_message").show();

                $('#contact_form input').val('');
            }, 'json');
        });