Bootstrap Contact Form with jQuery Validation and AJAX - javascript

I have a simple bootstrap contact form that I'm trying to implement with AJAX and jQuery validation. I feel like I'm pretty close but there are a few things that I can't get to work quite right. The forms validate according to input (ideally I'd like the phone number to be validated as digits; however, I'm new to contact form validation), but the contact form will still send even if the answers are not correct. In addition, the success box will always pop up after the form submits ... I'd like the form to not send if it is filled out incorrectly, and an error box to appear instead of the success. In addition, the email sends through the body of the message, but none of the variables get sent over. So the body of my message looks like:
Name:
Email:
Phone:
Message:
With no variable appear after each.
I know this may be something simple but I'm very new to form validation and I can't figure it out for the life of me.
Here's the HTML for the form:
<div class="form-group wow fadeInRight" data-wow-delay="1s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" id="name" name="name" placeholder="Name" />
</div>
</div>
</div>
<div class="form-group wow fadeInRight" data-wow-delay="1.1s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control" id="email" name="email" placeholder="Email" />
</div>
</div>
</div>
<div class="form-group wow fadeInRight" data-wow-delay="1.2s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone" />
</div>
</div>
</div>
<div class="form-group wow fadeInRight" data-wow-delay="1.3s">
<div class="controls">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea name="message" class="form-control " rows="4" cols="78" placeholder="Enter your message here."></textarea>
</div>
</div>
</div>
<div id="success"></div>
<div class="row wow fadeInUp" data-wow-delay="1.3s">
<div class="form-group col-xs-12">
<div class="contact-btns">
<input type="submit" class="submit-button" value="Submit" name="submit">
<input type="reset" class="clear-buttom" value="Clear" name="clear">
</div>
</div>
</div>
</form>
Here's the PHP:
$status = array(
'type' => 'success',
'message' => 'Email sent!'
);
$val = $_POST['val'];
$toemail = 'myemail#gmail.com';
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$msg = $_POST['message'];
$subject = 'Thelliotgroup Information Request';
$headers = "From: Thelliotgroup Website :: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<b>Name: </b>" . $name . "<br>";
$message .='<b>Email: </b>' . $email . "<br>";
$message .='<b>Phone: </b>' . $phone . "<br>";
$message .='<b>Message: </b>' . $msg;
$success = mail($toemail, $subject, $message, $headers);
echo json_encode($status);
die
Here's the AJAX and jQuery:
var form = $('.contact');
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function (data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
}, 'json');
return false;
});
$.validator.setDefaults({
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "email.php",
data: {'val': $(".contact").serializeJSON()}
}).done(function (data) {
alert(data);
});
}
});
$(".contact").validate(
{rules:
{name: "required",
email: {required: true, email: true},
phone: "required",
message: {required: true, maxlength: 300
}},
errorClass: "error",
highlight: function (label) {
$(label).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function (label) {
label
//.text('Seems Perfect!').addClass('valid')
.closest('.form-group').addClass('has-success');
}
});
I'd really appreciate any help you guys could give me to get this working properly.
Edit
Here's the new jQuery and AJAX code:
$(document).ready(function() {
var form = $(this);
var post_url = form.attr('action');
$('.contact').validate({
rules: {
name: {
rangelength: [2,40],
required: true
},
email: {
rangelength: [2,40],
email: true,
required: true
},
phone: {
rangelength: [7,10],
required: true
},
message: {
minlength: 30,
required: true
},
errorClass:"error",
highlight: function(label) {
$(label).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(label) {
label
.closest('.form-group').addClass('has-success');
}
},
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'email.php',
data: $(form).serialize(),
success: function(msg) {
$('.sent').fadeIn().fadeOut(5000);
}
});
return false;
}
});
});
Now I just need to figure out how to make it so that:
<div class="status alert alert-success" style="display: none"></div>
Which is located directly above the form, will fade in once the form is submitted.
I can't get it to work.
Thanks,
Brennan

I do not understand why you're doing a .post() (ajax) inside of a jQuery submit handler function while at the exact same time you have .ajax() inside of the plugin's submitHandler function. I don't get it. Why are you using ajax twice?
I think it's best that you remove this entire function...
form.submit(function () {
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
Because it is interfering with the plugin's submitHandler function.
Use the submitHandler to fire code upon the button click when the form is valid. This is where any ajax would belong.
EDIT:
You've put errorClass, highlight and success inside the rules option...
rules: {
name: {
....
},
email: {
....
},
phone: {
....
},
message: {
....
},
errorClass:"error",
highlight: function(label) {
....
},
success: function(label) {
....
}
},
This is wrong. errorClass, highlight and success are siblings of the rules and submitHandler options.
Also, when using highlight, it's best to use unhighlight along with it to undo whatever you did with highlight.
rules: {
// only your rules here
},
errorClass:"error",
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').addClass('has-success').removeClass('has-error');
},
submitHandler: function(form) {
$.ajax({
// your options
});
return false;
}
For clearing out the form within the Ajax success option...
$('#myform').validate().resetForm(); // reset validation
form[0].reset(); // clear out the form data

Related

How to get the success message in the same page after submitting the form?

I'm trying to display a success and error message in the same page. What do i need to change?
The form is to send the data to the database and then show a success message in the same page, then redirect to another page. I've tried changing the ID value in the form and the java script, i still get the same results, the data is sent to the database, it redirects to another page, but it doesn't show the success message before redirecting.
Controller:
public function register_ajax() {
//form validation rules
$this->form_validation->set_rules('org_name', 'Organisation Name',
'trim|required');
$this->form_validation->set_rules('email', 'Email',
'trim|required|valid_email|is_unique[new_church.email]',
array('is_unique' => "This email address is already registered
with this application.")
);
$this->form_validation->set_rules('password', 'Your Password',
'trim');
$this->form_validation->set_rules('c_password', 'Confirm Password',
'trim|required|matches[password]',
array(
'matches' => 'Password does not match'
)
);
if ($this->form_validation->run()) {
$this->registration_model->update_church(); //insert the data
into db
echo 1;
redirect(site_url('registration/payment'));
} else {
echo validation_errors();
}
}
Model:
public function update_church() {
$org_name = ucwords($this->input->post('org_name', TRUE));
$email = $this->input->post('email', TRUE);
$password = ucfirst($this->input->post('password', TRUE));
$c_password = ucfirst($this->input->post('c_password', TRUE));
$data = array (
'org_name' => $org_name,
'email' => $email,
'password' => $password,
'c_password' => $c_password,
);
$this->db->insert('new_church', $data);
//email admins
//$this->notify_admins($name, $email, $subject, $message);
}
JavaScript:
//Registration
$('#registration_form').submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: base_url + 'registration',
type: 'POST',
data: form_data,
success: function(msg) {
if (msg == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>').fadeIn( 'fast' );
$('#registration_form')[0].reset(); //reset form fields
} else {
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
}
});
});
View:
<?php
$form_attributes = array("id" => "registration_form");
echo form_open('registration/register_ajax', $form_attributes); ?>
<div class="login100-form validate-form">
<div class="wrap-input100 validate-input" data-validate = "First
name is required">
<label class="form_header">Organisation Name</label>
<input class="input100" type="text" name="org_name" value="<?php
echo set_value('org_name'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Valid
email is required: ex#abc.xyz">
<label class="form_header">Your Work Email Address</label>
<input class="input100" type="email" name="email" value="<?php
echo set_value('email'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Password
is required">
<label class="form_header">Your Password</label>
<input class="input100" type="password" name="password" value="<?
php echo set_value('password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Confirm Password">
<label class="form_header">Confirm Password</label>
<input class="input100" type="password" name="c_password" value="<?php echo set_value('c_password'); ?>" required/>
<span class="focus-input100"></span>
</div>
<div class="text-center p-t-12">
<p>By clicking the button below, you agree to StreamApp's terms of acceptable use</p>
</div>
<div class="m-t-20">
<div id="status_msg"></div>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn"> NEXT </button>
</div>
</div>
<?php echo form_close(); ?>
I expect a success message to appear before redirecting to another page
what happened to your code is when your try to run the form validation it get always true because you set a condition where not executing if the result is true or false.
if ($this->form_validation->run() == TRUE) { //you should change it to this
$this->registration_model->update_church();
$data['success'] = 1;
} else { //if the form validation run false it will display the error.
$data['error'] = validation_errors();
}
echo json_encode($data);
And if you are going to send back a message to your AJAX code you should encode it first using JSON.
To display it.. do this.
if (msg.success == 1) {
$('#status_msg').html('<div class="alert alert-success
text-center"> Success.</div>');
$('#registration_form')[0].reset(); //reset form fields
setTimeout(function(){
window.location.replace("<?php echo base_url('registration/payment') ?>");
}, 3000); //set it to your time
} else if(msg.error){
$('#status_msg').html('<div class="alert alert-danger
text-center">' + msg.error + '</div>').fadeIn( 'fast' ).delay(
30000 ).fadeOut( 'slow' );
}
Hope that helps.Let me know the result.
Remove this line:
redirect(site_url('registration/payment'));
And in your ajax success function add this:
if (response == "1") {
// todo set timeout maybe and show a success message then redirect.
window.location.href = siteUrl+"registration/payment";
}
And just make sure to define siteUrl in your js file:
const siteUrl = "http://localhost/";

Contact form doesn't validate inside bootstrap modal

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">×</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">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
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
}
});
});
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

Jquery empty results

Problem
I tried after submitting the form not redirect to email php. For that I used ajax and its somehow working however it's gives back empty result. I have problem with javascript but thats enough difficult to find for my beginner level. I tested to send email without ajax and it sending normally. But redirecting to empty page email.php
HTML
<form method="POST" id="myForm" data-toggle="validator" action="email.php">
<h2 class="section-heading">Свяжитесь с нами:</h2>
<div class="form-group">
<label for="exampleInputEmail1">Имя:</label>
<input style="background:none;" id="firstName" name="firtname" class="form-control" placeholder="Имя" required>
<p id="p1"></p>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Тема:</label>
<input style="background:none;" id="subjectTheme" name="subject" class="form-control" placeholder="Тема" required>
<p id="p2"></p>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Электронная почта:</label>
<input style="background:none;" type="email" id="email" name="email" class="form-control" placeholder="Электронная почта" required>
<p class="help-block with-errors"></p>
</div>
<div class="form-group">
<label>Сообщение:</label>
<textarea style="background:none;" name="message" class="form-control" rows="3"></textarea>
</div>
<input type="submit" id="sendButton" class="btn btn-default"/>
</form>
Javascript
$('#myForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'email.php'
});
$('#myForm')[0].reset();
alert("Success!");
})
PHP
<?php
$to = 'test#mail.ru'; // Replace with your email
$subject = $_POST['subject']; // Replace with your $subject
$headers = 'From: ' . $_POST['email'];
$message = 'Имя: ' . $_POST['firtname'] . "\n" .
'Электронная почта: ' . $_POST['email'] . "\n" .
'Тема: ' . $_POST['subject'] . "\n" .
'Сообщение: ' . $_POST['message'];
mail($to, $subject, $message, $headers);
?>
You need to pass the informations through AJAX. And reset your form on AJAX success. You didn't do that now.
Should look like this:
$('#myForm').submit(function(e) {
e.preventDefault();
var firstname = $('#firstName').val();
var subject = $('#subjectTheme').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: 'POST',
url: 'email.php',
data: {firstname: firstname, subject: subject, email: email, message: message },
success: function(){
$('#myForm')[0].reset();
alert("Success!");
}
});
})
You need to pass the content of the form and move the alert and reset to the callback:
$('#myForm').on("submit",function(e) {
e.preventDefault();
$.post(
$(this).attr("action"),
$(this).serialize(),
function(response) {
alert("success");
$('#myForm')[0].reset();
}
);
});
Your email.php file should send a status message to your ajax based on mail is sent or not. You should send your form data to email.php file.
your script
$('#myForm').on("submit",function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'email.php',
data: $('#myForm').serialize(),
success: function(data) {
if(data == 'success') {
alert('mail sent success');
$('#myForm')[0].reset();
} else {
alert('failed');
}
}
});
your PHP
<?php
...
...
if(mail($to, $subject, $message, $headers)) {
$status = 'success';
} else {
$status = 'failed';
}
die($status);
?>

$_POST[] not catching HTML form input

I have a strange problem, I am passing data from an email form (HTML5) to ajax/JSON and returning false so the page does not redirect to the php script after the submit button is pressed.
If I put commas seperating each data param ($email, $name, $message), only 'name' and 'email' get passed to $_POST[], leaving out the value of$message.
However if there are no commas between the params all the inputs are caught by $_POST[].
For example (with commas): (does not redirect to php script but $message value is not caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
Output:
$name=foo
$email=bar
$message=null
Page returns false
(without commas): (redirects to php script but $message value is caught in $_POST[])
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',{
name: $('input[name=name]').val()
email: $('input[name=email]').val()
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false; (does not redirect to `php`)
});
Output:
$name=foo
$email=bar
$message=bar
HTML Form:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="Scripts/php/sendemail.php">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-danger btn-lg">
Send Message
</button>
</div>
</div>
</div>
</form>
JS for form:
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('input[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
PHP handler:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent! Thankyou :)'
);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = 'query';
$message = $_POST['message'];
$email_from = $email;
$email_to = 'keilcarpenter01#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = mail($email_to, $subject, $body, 'From: visitor');
echo json_encode($status);
#start buffering (all activity to the buffer)
ob_start() ;
# dumps to buffer
var_dump($_POST) ;
# dump buffered $classvar to $outStringVar
$outStringVar = ob_get_contents() ;
# open your file with append, read, write perms
# (be sure to check your file perms)
$fp=fopen('dmp.txt','a+');
# write output to file & close it
fwrite($fp, $outStringVar );
fclose($fp);
# clean the buffer & stop buffering output
ob_end_clean() ;
die;
In this case how does the comma seperatores determine what input by form gets caught by $_POST[]?
You have to change the jquery for get value of textarea, try following code for that :-
var form = $('.contact-form');
form.submit(function (evt) {
$this = $(this);
$.post('Scripts/php/sendemail.php',
{name: $('input[name=name]').val(),
email: $('input[name=email]').val(),
message: $('textarea[name=message]').val()
}, function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
evt.preventDefault();
return false;
});
It may help you.
Use:
message: $('textarea[name=message]').val()

Bootbox is not working when calling a modal form

I am using bootbox modal for calling a modal form but form is not appeared as a modal. Nothing happens when we click compose. I want to open a form in a model after clicking the compose button but its not working.
<a class="btn btn-block btn-compose btn-lg" id="loginButton"><i class="fa fa-" ></i> Compose Mail </a>
<!-- The login modal. Don't display it initially -->
<form id="loginForm" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-xs-3 control-label">To</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="to" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Subject</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="ssubject" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Message</label>
<div class="col-xs-5">
<textarea name="smessage" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</form>
This is html form and the java script file are placed in same page inbox.php
$(document).ready(function() {
$('#loginForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
to: {
validators: {
notEmpty: {
message: 'Please type destination bo'
}
}
},
ssubject: {
validators: {
notEmpty: {
message: 'Please type subject'
}
}
},
smessage: {
validators: {
notEmpty: {
message: 'Please type some message'
}
}
}
}
});
// Login button click handler
$('#loginButton').on('click', function() {
bootbox
.dialog({
title: 'Compose Message',
message: $('#loginForm'),
show: true // We will show it manually later
})
.on('shown.bs.modal', function() {
$('#loginForm')
.show() // Show the login form
.formValidation('resetForm', true); // Reset form
})
.on('hide.bs.modal', function(e) {
// Bootbox will remove the modal (including the body which contains the login form)
// after hiding the modal
// Therefor, we need to backup the form
$('#loginForm').hide().appendTo('body');
})
.modal('show');
});
});
</script>
<script>
$(document).ready(function() {
$('#loginForm').on('success.form.fv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
validator = $form.data('formValidation'),
username = validator.getFieldElements('username').val();
// Hide the modal containing the form
$form.parents('.bootbox').modal('hide');
// Show the welcome dialog
// Use Ajax to submit form data
$.ajax({
//url: $form.attr('action'),
url: 'test/send.php',
type: 'POST',
data: $form.serialize(),
success: function(result) {
//alert(result);
//bootbox.alert('Welcome back, ' + username);
bootbox.alert(result);
window.location.reload();
}
});
});
});
</script>
and here's the test/send.php code.
<?php
$from="0";
$to=$_POST["to"];
$subject=$_POST["ssubject"];
$message=$_POST["smessage"];
//echo $to.$message;
//validate before insert
if(strlen($subject)>50){
echo "Subject was too long";
die();
}
if(strlen($message)>150){
echo "Message was too long";
die();
}
include('../dbsource.php');
$mysqli=connect();
if(insert($mysqli,$from,$to,$subject,$message)>0)
echo "Message was sent";
else
echo "Message was not sent";
?>
<?php
function insert($mysqli,$from,$to,$subject,$message){
$mdate=date('Y-m-d');
$mtime=date('H:i:s');
$query = "INSERT INTO messages (mfrom,mto,subject,message,mdate,mtime)".
"VALUES ('$from','$to','$subject','$message','$mdate','$mtime')";
if($mysqli->query($query)>0)
return($mysqli->insert_id);
else
return 0;
}
?>
The modal does not appear.
I dont know why is the modal is not appearing in this project.
Can anybody help me ?
error in console:

Categories