6

I'm trying to make an html page with bootstrap and bootstrap validator.

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. 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 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 :

<?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);
}?>
Gurol
  • 61
  • 6

3 Answers3

2

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.

  • Thanks for your answer but i'm a beginner and i don't know how i need to do this... Can you help me a little more ? – Gurol Jan 27 '16 at 15:07
  • Right then, find the button on the form that set as ```type='submit'``` and change it to ```type='button'``` - this prevents the form being submitted (and instead just treats the button as a button. Next in the ```function verif()``` amend the start of it thusly. ```function verif() { $('#contact').preventDefault(); $('#contact').bootstrapvalidator(...... etc etc ``` – Sgt Oddball Jan 27 '16 at 15:19
  • Like this ? `function verif() { $('#contact') .preventDefault({ }) .bootstrapValidator({ live: 'disabled', message: 'Cette valeur est invalide', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validat...` i've got an error : `Uncaught TypeError: $(...).preventDefault is not a function` – Gurol Jan 27 '16 at 15:52
  • Nope, notice how the prevent default doesn't have any curly braces inside of the brackets. It doesn't need it. Also you'd tried to chain the preventDefault with the bootstrapvalidator. You're generally better declaring each separately. – Sgt Oddball Jan 27 '16 at 17:04
1

Comment this line : 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');
        });
Monty
  • 1,110
  • 7
  • 15
  • i tried but where i need to put my "envoimail()" function ? – Gurol Jan 27 '16 at 15:04
  • check my modified answer. @Gurol – Monty Jan 28 '16 at 04:33
  • not working. When I click the button, the envoimail () function will be launched as many times as I have to input – Gurol Jan 28 '16 at 15:04
  • did you checked manual of this bootstrapvalidator ?? If not check it you will find my answer. – Monty Jan 28 '16 at 15:30
  • In fact, the function work for the error part but not for the success. If a field is in error, everything is ok but when all the fields are good, the function is loaded for every field (6 field - 6 launch). I don't find any information on the manual about the success part. i'm sorry but i'm a real beginner. I try to understand but it's difficult. – Gurol Jan 29 '16 at 08:33
0

Change the button type from "submit" to "button", then in the javascript you can add this if condition

if($('#contact').validate().form()){
    envoimail();
});
SnareChops
  • 13,175
  • 9
  • 69
  • 91