Bootbox is not working when calling a modal form - javascript

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:

Related

Inserting data in Textarea into database with Ajax

I'm doing a form submission with AJAX. Input values in the form are inserted into the database without any problems. However, the text (data) I write in the textarea is not inserted into the database. I think this is due to the script I wrote. I did some research but couldn't find any resource on this issue. I wonder why the data in the textarea is not inserted into my database?
My script :
<script>
function NewTicket() {
var ticket = $("#newticket").serialize();
$.ajax({
type : "POST",
data : ticket,
url : "ajax.php",
success : function (e) {
if ($.trim(e) == "success") {
swal({
title: "Success",
text: "Gotcha",
icon: "success",
closeOnClickOutside: false,
buttons: false,
timer: 3000
});
$("#new_ticket").hide();
$("#success").show();
} else if ($.trim(e) == "error") {
swal({
title: "Error",
text: "Something went wrong.",
icon: "error",
closeOnClickOutside: false,
buttons: false,
timer: 3000
});
}
}
});
}
</script>
<script src="/js/simplemde.min.js"></script>
<script>
new SimpleMDE({
element: document.getElementById("textarea"),
spellChecker: false,
hideIcons: ['side-by-side', 'fullscreen', 'preview', 'guide', 'image', 'link'],
});
</script>
HTML :
<form action="" id="newticket" onsubmit="return false;" name="newticketlo" method="POST">
<h4>New Ticket</h4>
<div class="Name">
<label class="form-label">Name</label>
<input type="text" class="form-control form-primary" >
</div>
<div class="EmailAddress">
<label class="form-label">Email</label>
<input type="text" class="form-control form-primary" >
</div>
<div class="col-12 col-md-12 mb-3">
<label class="form-label">Subject</label>
<input type="text" class="form-control form-primary" name="subject">
</div>
<div class="col-12 col-md-12 mb-4">
<label class="form-label">Message</label>
<textarea class="form-control form-primary" id="textarea" name="message"></textarea>
</div>
<input type="hidden" name="id" value="<?= $getData['id']; ?>">
<div class="Settin">
<button onclick="NewTicket();" class="btn btn-two btn-rounded font-weight-semibold text-3 btn-px-5 btn-py-2 d-none d-md-block me-3 me-lg-0 mb-4">Submit</button>
</div>
PHP :
if ($_POST) {
$customer_id = (trim(strip_tags($_POST['id'])));
$subject = (strip_tags($_POST['subject']));
$message = nl2br(htmlentities($_POST['message'], ENT_QUOTES, 'UTF-8'));
$query=$db->prepare("INSERT INTO support SET
customer_id=:customer_id,
subject=:subject,
message=:message
");
$update=$query->execute(array(
'customer_id' => $customer_id,
'subject' => $subject,
'message' => $message,
));
if ($update) {
echo "success";
} else {
echo "error";
}
}else {
echo "error";
}
Ah, now I fixed the problem! The problem is that the "message" column in the database is TEXT. I did VARCHAR and it was fine. Now everything works smoothly.
But one more problem occurred.
Message data is not sent when submitting the form for the first time. But on the second try, the message data is inserted into the database. Why is the message data not being inserted into the database on the first try? It's frustrating to try twice. What is causing this?

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

Codeigniter jquery ajax: post data to controller issues

I'm working on login system in codeigniter 3.0 and jquery ajax. I want to post data to controller using ajax and return a value if the data thrown by ajax is match from the mysql database. I also try those suggestion/s from this existing post but i think its not working. I don't want to rely the redirect from codeigniter.
MAIN PROBLEM: i want to check if the username and password data are incorrect, it prompts an error with no page refresh. But i did was throw an boolean value from controller to view for projecting an error-like html tag.
heres the code:
readyLogin.js
var ReadyLogin = function () {
return {
init: function () {
/*
* Jquery Validation, Check out more examples and documentation at https://github.com/jzaefferer/jquery-validation
*/
/* Login form - Initialize Validation */
$('#form-login').validate({
errorClass: 'help-block shake animated', // You can change the animation class for a different entrance animation - check animations page
errorElement: 'div',
errorPlacement: function (error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function (e) {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
},
rules: {
'login-username': {
required: true
},
'login-password': {
required: true,
minlength: 5
}
},
messages: {
'login-username': {
required: "Please enter Administrator's username."
},
'login-password': {
required: "Please provide Administrator's password.",
minlength: 'Your password must be at least 5 characters long.'
}
}
});
$("#form-login").submit(function(){
$.ajax({
type: "POST",
url: $('#form-login').attr('action'),
data: {"login-username": $("#login-username").val(), "login-password": $("#login-password").val()},
dataType: "json",
success: function (returnData) {
alert(data); // to check if there's a thrown data from the view to controller
// below is a "trial" code that checks the status if the controller receives data from ajax
if (returnData.status == true) {
console.log(returnData.status);
} else {
console.log('empty');
}
}
});
});
}
};
}();
controller/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
}
public function index() {
$data['error'] = false;
$result = $data['error'];
if ($_POST) {
$this->load->model('Login_model');
$username = $this->input->post('login-username', true);
$password = $this->input->post('login-password', true);
$user = $this->Login_model->login($username, $password);
if (!$user && $user == null) {
$data['error'] = true; //throwing boolean value to make error html tag
$result = array('status' => true);
json_encode($result);
} else {
$data['error'] = false;
$this->session->set_userdata('username', $user['usename']);
$this->session->set_userdata('password', $user['password']);
redirect(base_url() . 'Maps');
}
}
$this->load->view('Backend/page_ready_login', $data);
}
function logout() {
$this->session->sess_destroy();
redirect(base_url(), 'refresh');
}
}
model/Login.php
<?php
class Login_model extends CI_Model {
function login($username,$password){
$where=array(
'username'=>$username,
'password'=>sha1($password)
);
$this->db->select()->from('admin')->where($where);
$query=$this->db->get();
return $query->first_row('array');
}
}
views/Backend/page_ready_login.php
<?php
include 'assets/Backend/inc/config.php';
$template['title'] = 'BCGIS | LOGIN';
$template['page_preloader'] = true;
?>
<?php include 'assets/Backend/inc/template_start.php'; ?>
<!-- Login Container -->
<div id="login-container">
<!-- Login Header -->
<h1 class="h3 text-light text-center push-top-bottom fadeIn animated">
<div class="row">
<div class="col-lg-3 fadeIn animated">
<img src="<?= base_url(); ? >assets/Backend/images/Ph_seal_davao_del_norte_panabo_city.png" style="width: 95px; height: 80px;"/>
</div>
<div class="col-lg-9 fadeIn animated">
<strong>Brgy. Cagangohan Geographical Information System</strong>
</div>
</div>
</h1>
<!-- END Login Header -->
<!-- Login Block -->
<div class="block fadeIn animated">
<!-- Login Title -->
<div class="block-title">
<h2>Administration Login</h2>
</div>
<!-- END Login Title -->
<!-- Login Form -->
<form id="form-login" action="<?= base_url(); ?>" method="post" class="form-horizontal">
<?php if ($error == true) { ?>
<h5 class="alert alert-danger shake animated" id="login-error">Your Username/Password is incorrect!</h5>
<?php } ?>
<div class="form-group">
<div class="col-xs-12">
<input type="text" id="login-username" name="login-username" class="form-control" placeholder="Username..">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input type="password" id="login-password" name="login-password" class="form-control" placeholder="Password..">
</div>
</div>
<div class="form-group form-actions">
<div class="col-sm-offset-2 col-sm-8 text-center">
<center>
<button type="submit" id="login-button" name="login-button" class="btn btn-effect-ripple btn-block btn-primary"><i class="fa fa-check"></i> Sign In</button>
</center>
</div>
</div>
</form>
<!-- END Login Form -->
</div>
<!-- END Login Block -->
<!-- Footer -->
<footer class="text-muted text-center fadeIn animated">
<small><span id="year-copy"></span> © <?php echo $template['name'] . ' ' . $template['version']; ?></small>
</footer>
<!-- END Footer -->
</div>
<!-- END Login Container -->
<?php include 'assets/Backend/inc/template_scripts.php'; ?>
<!-- Load and execute javascript code used only in this page -->
<script src="<?= base_url(); ?>assets/Backend/js/pages/readyLogin.js"> </script>
<script>
$(function () {
ReadyLogin.init();
});
</script>
<?php include 'assets/Backend/inc/template_end.php'; ?>
Any suggestion/s and help fixing this is much appreciated. Thanks.
In your controller method, change this:
if (!$user && $user == null) {
To this:
if (!$user || $user == null) {

Bootstrap Contact Form with jQuery Validation and AJAX

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

how to submit form after ajax response of submitting another form?

I have a form that is a file input:
<form method="post" id='careerform' action="<?php echo Yii::app()->createUrl('site/career'); ?>" enctype="multipart/form-data">
<input type="file" name="cv" id="cv">
<input type="button" id="submitcareer" class="btn btn-default pull-right" data-toggle="modal" data-target=".bs-example-modal-sm" value="Submit">
</form>
when the user clicks on submit, the form will be checked for validation:
<script type="text/javascript">
$(document).ready(function() {
$('#careerform').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
cv: {
validators: {
notEmpty: {
message: 'CV is required.'
},
file: {
extension: 'doc,docx,pdf,zip,rtf',
type: 'application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf,application/zip',
maxSize: 5 * 1024 * 1024,
message: 'The selected file is not valid, it should be (doc,docx,pdf,zip,rtf) and 5 MB at maximum.'
},
}
}
}
});
$('#submitcareer').click(function(){
$('#careerform').data('bootstrapValidator').validate();
if($("#careerform").data('bootstrapValidator').isValid()){
$('#modalbtn').click();
}
});
});
</script>
then a modal will appear, the modal contains a form that include google recaptcha inputs:
<div class="modal-body">
<form method="post" id="modalform" enctype="multipart/form-data">
<?php
require_once(Yii::app()->basePath.'/extensions/recaptchalib.php');
$publickey = "...";
echo recaptcha_get_html($publickey);
?>
<button type="submit" class="btn btn-primary" id="modalsubmit" >Submit</button>
</form>
</div>
<div class="modal-footer">
<script type="text/javascript">
$(document).ready(function() {
$("#modalsubmit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"<?php echo Yii::app()->createUrl('site/verify'); ?>",
data:$("#modalform").serialize(),
dataType: 'json',
async: false,
success:function(response){
if(response == 2){
$('#careerform').data('bootstrapValidator').validate();
if($("#careerform").data('bootstrapValidator').isValid()){
$('#careerform').submit();
}
}
}
});
});
});
</script>
</div>
the ajax response will be 2 if the user entered the captcha correctly, then the first form should submitted.
my problem that is the first form is not submitted when I am getting a response value = 2, so what is the problem here? is there another way to do what I want ?
Determine which type is response. jQuery is trying to convert the response as a JSON object if dataType is set to JSON.

Categories