简体   繁体   English

带模态,验证器和电子邮件的Bootstrap表单

[英]Bootstrap form with modal, validator and email

I'm trying to make an html page with bootstrap and bootstrap validator. 我正在尝试使用bootstrap和bootstrap验证器创建一个html页面。

What i want to do : When the user click on the button, a modal appear with a form. 我想做的事情:当用户点击按钮时,会出现一个带有表单的模态。 After validation, form sent an email with the fields value. 验证后,表单发送了一个包含字段值的电子邮件。 When the mail was correctly sent, an other modal appear with some informations 正确发送邮件后,会出现其他模式,其中包含一些信息

My problem : my script with bootstrap validator doesn't work. 我的问题:我的脚本与bootstrap验证器不起作用。 When a field is in error, the form is sent every time the error appear. 当字段出错时,每次出现错误时都会发送表单。 If i complete all the fields, the page reboot and nothing work. 如果我完成所有字段,页面重新启动,没有任何工作。

please, can you help me to find my mistake ? 拜托,你能帮我找到我的错吗?

my html : 我的HTML:

<html lang="fr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title></title>

<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<style type="text/css">

</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrapValidator.js"></script>

<script language="JavaScript">
<!--vérif formulaire-->

        function verif() {
            $('#contact')
            .bootstrapValidator({
                live: 'disabled',
                message: 'Cette valeur est invalide',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    e1: {
                        validators: {
                            notEmpty: {
                                message: 'Votre nom est obligatoire'
                            }
                        }
                    },
                    e2: {
                        validators: {
                            notEmpty: {
                                message: 'Votre prenom est obligatoire'
                            }
                        }
                    },
                    e3: {
                        validators: {
                            notEmpty: {
                                message: 'Votre adresse mail est obligatoire'
                            },
                            /*emailAddress: {
                            message: 'Le format de votre adresse mail n est pas valide'
                            }*/
                        }
                    },
                    e4: {
                        validators: {
                            notEmpty: {
                                message: 'Votre numero de telephone est obligatoire'
                            }
                        }
                    },
                    /*homePhone: {
                        validators: {
                            digits: {
                                message: 'The home phone number is not valid'
                            }
                        }
                    },*/
                }
            })
            .on('error.form.bv', function(e) {
                console.log('error.form.bv');

                var $form = $(e.target);
                console.log($form.data('bootstrapValidator').getInvalidFields());

            })
            .on('success.form.bv', function(e) {
                console.log('success.form.bv');
                envoimail();
            })

        }

        function envoimail() {
            alert("lancement mail ok");
            $.ajax({
                type: "POST",
                url: "process.php",
                data: $('form.contact').serialize(),
                success: function(msg){
                    $("#thanks").html(msg);
                    alert("thanks ok");
                    $("#myModal").modal('hide');
                    alert("hide ok");
                    $("#synthese").modal('show');
                    alert("show ok");
                },
                error: function(){
                    alert("Echec de l envoi du formulaire");
                },
            }); 
        };

    </script>

</head>
<body>
    <div>
        <button type="button" class="btn btn-primary btn-lg center-block" data-toggle="modal" data-target="#myModal">
          Lancer le calcul
        </button>
    </div>

    <div id="thanks">
        <p>test</p>
    </div>

    <br>

<!-- Modal 1 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Quelques informations sur vous :</h4>
                </div>

                <div class="modal-body">
                    <form id="contact" class="form-horizontal contact" name="contact">
                        <div class="form-group">
                            <label class="col-lg-4 control-label">Nom</label>
                            <div class="col-lg-6">
                                <input class="form-control" id="e1" name="e1" type="text" style="text-align:left" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-lg-4 control-label">Prénom</label>
                            <div class="col-lg-6">
                                <input class="form-control" id="e2" name="e2" type="text" style="text-align:left" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-lg-4 control-label">Fonction</label>
                            <div class="col-lg-6">
                                <input class="form-control" id="e5" name="e5" type="text" style="text-align:left"/>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-lg-4 control-label">Email</label>
                            <div class="col-lg-6">
                                <input class="form-control" id="e3" name="e3" type="text" style="text-align:left" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-lg-4 control-label">Téléphone</label>
                            <div class="col-lg-6">
                                <input class="form-control" id="e4" name="e4" type="text" style="text-align:left" />
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-lg-4 control-label">Message</label>
                            <div class="col-lg-6">
                                <input class="form-control" id="e6" name="e6" type="text" style="text-align:left" />
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-lg-12">
                                <button type="submit" id="resultat" class="btn btn-primary btn-lg center-block" onclick="verif()" >Afficher le résultat</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

<!-- Modal 2 -->    
    <div class="modal fade" id="synthese" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Synthèse :</h4>
                </div>

                <div class="modal-body">

                    <div class="modal-body">
                        <button type="button" class="btn right" data-dismiss="modal" style="float:right;">Relancer</button>
                    </div>

                    <br>

                </div>
            </div>
        </div>
    </div>
    <script src="js/bootstrap.min.js"></script>
</body>

My process.php : 我的process.php:

<?php
$myemail = 'mail@domaine.fr';
if (isset($_POST['e1'])) {
$e1nom = strip_tags($_POST['e1']);
$e2prenom = strip_tags($_POST['e2']);
$e3mail = strip_tags($_POST['e3']);
$e4tel = strip_tags($_POST['e4']);
$e5fonction = strip_tags($_POST['e5']);
$e6message = strip_tags($_POST['e6']);
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<stong>Nom : </strong> ".$e1nom."<br>";   
echo "<stong>Prenom: </strong> ".$e2prenom."<br>";  
echo "<stong>Mail : </strong> ".$e3mail."<br>";
echo "<stong>Tel : </strong> ".$e4tel."<br>";   
echo "<stong>Fonction : </strong> ".$e5fonction."<br>";
echo "<stong>Message : </strong> ".$message."<br>"; 

$to = $myemail;
$email_subject = "Lancement du simulateur de prix PPE";
$email_body = "Lancement d une nouvelle simulation. \n\n".
" Detail de la simulation :\n\n".
" Nom : $e1nom \n".
" Prenom : $e2prenom \n".
" Mail : $e3mail \n".
" Tel : $e4tel \n".
" Fonction : $e5fonction \n".
" Message :\n $e6message";
$headers = "From: mail@domaine.fr\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
}?>

When it comes to forms through javascript you should always validate serverside as well anyway (since you can't trust anything the visitor sends you), that aside, there's nothing to stop the form submitting when the submit button is used. 当谈到表单时,你应该总是验证服务器端(因为你不能信任访问者发送给你的任何东西),除此之外,没有什么能阻止使用提交按钮时表单提交。

So either change the form buttons type to 'button' instead of 'submit' or in the start of your validation add something to stop the form from running it's default action. 因此,要么将表单按钮类型更改为“按钮”而不是“提交”,要么在验证开始时添加一些内容以阻止表单运行默认操作。 Something along the lines of - 有点像 -

function verif(){$('#contact').preventDefault();$('#contact')....

Or even better, use both. 或者甚至更好,同时使用两者。 That way the form won't be submitted until the checks have been run against the form no matter how. 这样,在对表格进行检查之前,表单将不会被提交,无论如何。

Comment this line : live: 'disabled', 评论此行: live:'disabled',

Suggestion : 建议:

1.) // Validate the form manually
        $('#resultat').click(function() {
            $('#contact').bootstrapValidator('validate');
        });

2.) write your code in document.ready function.

Modified : 修改:

.on('error.field.bv', function(e, data) {
     //console.log('error.field.bv -->', data.element);
 })
.on('success.field.bv', function(e, data) {
     //console.log('success.field.bv -->', data.element);
     // envoimail();
 })

.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('process.php', $form.serialize(), function(result) {
                console.log(result);
            }, 'json');
        });

Change the button type from "submit" to "button", then in the javascript you can add this if condition 将按钮类型从“提交”更改为“按钮”,然后在javascript中,您可以添加此条件

if($('#contact').validate().form()){
    envoimail();
});

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

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