0

So I have made a contact form using the example at https://bootstrapious.com/p/how-to-build-a-working-bootstrap-contact-form which works fine when placed on a page, however when I place it inside a bootstrap popup modal, the validator doesn't work. If all fields are empty and submit button hit, it will say 'message sent' even though it did not send, and if you fill in the fields it will still send and give success message also.

Also, if I hit the button to open modal as soon as page loads but before the script has loaded, it will work, so it's obviously because the modal is not visible when the validator script loads, so it misses it.

If anyone has some answers it would be super helpful as I'm pretty new to PHP and JS!

Here is my modal HTML

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close"
data-dismiss="modal" type="button"><span aria-hidden=
"true">&times;</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="../contact.php" id="contact-form" method="post" name=
"contact-form">
<div class="messages"></div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_name">Firstname *</label>
<input class="form-control" data-error="Firstname is required." id="form_name"
name="name" placeholder="Please enter your first name" required="required"
type="text">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_email">Email *</label> <input class=
"form-control" data-error="Valid email is required." id="form_email" name=
"vemail" placeholder="Please enter your email" required="required" type=
"email">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group"><label for="form_message">Message *</label> 
<textarea class="form-control" data-error="Please,leave us a message." id=
"form_message" name="message" placeholder="Please enter your message" required=
"required" rows="4"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12"><input class="btn btn-success btn-send" type="submit"
value="Send message"></div>
</div>
</form>
</div>
</div>
<!-- /.modal-content --></div>
<!-- /.modal-dialog --></div>
<!-- /.modal -->
</body>
</html>

This is my PHP file

<?php

// configure

$from = '<mail@myemail.net>'; 
$sendTo = 'Demo contact form <mail@myemail.net>';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'vemail' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';    

$email = ($_POST["vemail"]);
$subject2 = 'Thank you for contacting support.';
$msg = "Thank you for contacting Support. We have received your contact form and will be in contact as soon as possible";
$headers = 'Reply-To: mail@myemail.net' . "\r\n" ;    

// let's do the sending

try
{
    $emailText = "You have new message from contact form\n=============================\n";
       foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

   mail($email, $subject2, $msg, $headers) && mail($sendTo, $subject, $emailText, "From: " . $from);

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');        
    echo $encoded;
}
else {
    echo $responseArray['message'];
}
 ?>

And JS

$(function () {

    $('#contact-form').validator();

    $('#contact-form').on('submit', function (e) {
        if (!e.isDefaultPrevented()) {
            var url = "../contact.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#contact-form').find('.messages').html(alertBox);
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});
ArK
  • 20,698
  • 67
  • 109
  • 136
Tim
  • 1
  • 1
  • Maybe put `.validator('update')` (https://1000hz.github.io/bootstrap-validator/#validator-methods) in your call that opens the modal? – ourmandave Oct 17 '16 at 13:33

2 Answers2

0

Put your ajax call inside the validation process and use submitHandler.

This answer by @Sparky might save your day https://stackoverflow.com/a/15625824/6952155

Please refer to this and edit to suit in your code.

$(document).ready(function () {

 $("#contactform").validate({
     ignore: ":hidden",
     rules: {
         name: {
             required: true,
             minlength: 3
         },
         cognome: {
             required: true,
             minlength: 3
         },
         subject: {
             required: true
         },
         message: {
             required: true,
             minlength: 10
         }
     },
     submitHandler: function (form) {
         alert('valid form submission'); // for demo
         $.ajax({
             type: "POST",
             url: "formfiles/submit.php",
             data: $(form).serialize(),
             success: function () {
                 $(form).html("<div id='message'></div>");
                 $('#message').html("<h2>Your request is on the way!</h2>")
                     .append("<p>someone</p>")
                     .hide()
                     .fadeIn(1500, function () {
                     $('#message').append("<img id='checkmark' src='images/ok.png' />");
                 });
             }
         });
         return false; // required to block normal submit since you used ajax
     }

 });

 });
Community
  • 1
  • 1
Royts
  • 501
  • 6
  • 14
0

Ondrej here, author of the tutorial on Bootstrapious.

I have just found out that there was an error in Bootstrap validator and it was not working correctly in combination with the Bootstrap modal.

The solution is downloading the latest version from https://github.com/1000hz/bootstrap-validator, currently 0.11.5.

Best,

Ondrej