I get jQuery error while submitting my bootstrap form - javascript

I have a small registration form and I try to submit this form using submitHandler of bootstrap but it gave me a Uncaught TypeError: Cannot read property 'attr' of null.
I use this code to validate and submit :
$(document).ready(function(){
//To validate the registration form and save its value after validation
$('#registerForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
email: {
validators: {
notEmpty: {
message: 'The email is required and cannot be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The password is required and cannot be empty'
}
}
},
submitHandler: function(form) { // <- only fires when form is valid
$.ajax({
type: 'POST',
url: 'include-ajax/check_and_save_registration_form.php',
data: $(form).serialize(),
success: function() {
$(form).fadeOut(500, function(){
$(form).html("USER DONE!").fadeIn();
});
}
}); // <- end '.ajax()'
return false; // <- block default form action
}
}
});
});
Why do I get that error ? When I remove the submitHandler I do not get that error but I need it to store form data in my database.
The data validated correctly but not submitted.
I used also submitHandler: function(validator, form, submitButton).
Still giving the same error.
How to submit the form without getting error?
my for html :
<div class="pages_container">
<form id="registerForm" method="post" class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-6">
<input class="form-control" name="email" type="email" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Password</label>
<div class="col-lg-6">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Retype password</label>
<div class="col-lg-6">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
<div class="form-group">
<div class="col-lg-6 col-lg-offset-3">
<button type="submit" class="btn btn-primary btn-lg btn-block">Register</button>
</div>
</div>
</div>
</form>
</div>

Please see this page for the proper way to submit a form via ajax: Using Ajax to Submit the Form
$(document).ready(function() {
$(form)
.bootstrapValidator({
... options ...
})
.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($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
}, 'json');
});
});

Related

Form validation and all subsequent code doesn't execute

I have an update form,that i call inside a modal on my main page,(with an onclick event,the click triggers a call with xmlhttprequest for the edit page containing the form with the stored data values). The thing is,everything works fines,the update works,post works,retrieving data in the first place works,except for the form validation,and ajax use to post the data. Please notice that on my main page,i have a create call,that creates a new instance,and it works just fine,with the form validation and the ajax post,so it can't be some required jQuery or any other script.
This is my form:
<form id="eventFormUpdate" method="POST" class="form-horizontal" action="Event/{{$event->id}}/Update">
<input type="hidden" name="_method" value="PATCH" id="hidden-update">
<div class="form-group">
<label class="col-xs-3 control-label">Nom</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="nameUpdate" value="{{$event->name}}"/>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Date de début</label>
<div class="col-xs-5 dateContainer">
<div class="input-group input-append date" id="startDatePickerUpdate">
<input type="text" class="form-control" name="starting_dateUpdate" value="{{$event->starting_date}}"/>
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Date de fin</label>
<div class="col-xs-5 dateContainer">
<div class="input-group input-append date" id="endDatePickerUpdate">
<input type="text" class="form-control" name="ending_dateUpdate" value="{{$event->ending_date}}"/>
<span class="input-group-addon add-on"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Assigné à</label>
<div class="col-xs-5 selectContainer">
<select name="assigned_toUpdate" class="form-control">
<option value="4" selected >First</option> <!--fix this by checking if is the selected data or not-->
</select>
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Description</label>
<div class="col-xs-5">
<textarea id="descUpdate" class="form-control" name="descriptionUpdate" placeholder="Veuillez entrer une description">{{$event->description}}</textarea>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default" id="update-event-submit">valider</button>
</div>
</div>
</form>
And here is my script that handles the form validation and the ajax posting
<!-- event update script -->
<script>
$(document).ready(function() {
$('#startDatePickerUpdate')
.datepicker({
format: 'yyyy/mm/dd'
})
.on('changeDate', function(e) {
// Revalidate the start date field
$('#eventFormUpdate').formValidation('revalidateField', 'starting_dateUpdate');
});
$('#endDatePickerUpdate')
.datepicker({
format: 'yyyy/mm/dd'
})
.on('changeDate', function(e) {
$('#eventFormUpdate').formValidation('revalidateField', 'ending_dateUpdate');
})
.find('[name="assigned_toUpdate"]')
.selectpicker()
.change(function(e) {
/* Revalidate the pick when it is changed */
$('#eventFormUpdate').formValidation('revalidateField', 'assigned_toUpdate');
})
.end();
$('#eventFormUpdate')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
nameUpdate: {
validators: {
notEmpty: {
message: 'Le nom est obligatoire.'
}
}
},
starting_dateUpdate: {
validators: {
notEmpty: {
message: 'La date de début est obligatoire.'
},
date: {
format: 'YYYY/MM/DD',
min: new Date(new Date().setDate(new Date().getDate()-1)),
max: 'ending_date',
message: 'La date de début est non valide.'
}
}
},
ending_dateUpdate: {
validators: {
notEmpty: {
message: 'La date est oligatoire.'
},
date: {
format: 'YYYY/MM/DD',
min: 'starting_date',
message: 'La date de fin est non valide.'
}
}
},
descriptionUpdate: {
validators: {
notEmpty: {
message: 'La description est obligatoire.'
}
}
},
assigned_toUpdate: {
validators: {
notEmpty: {
message: 'Veuillez séléctionner un utilisateur.'
}
}
}
}
})
.on('success.field.fv', function(e, data) {
if (data.field === 'starting_dateUpdate' && !data.fv.isValidField('ending_dateUpdate')) {
// We need to revalidate the end date
data.fv.revalidateField('ending_dateUpdate');
}
if (data.field === 'ending_dateUpdate' && !data.fv.isValidField('starting_dateUpdate')) {
// We need to revalidate the start date
data.fv.revalidateField('starting_dateUpdate');
}
})
.submit(function(){
return false;
})
.submit(function(){
console.log('gonnastartsub');
var $form = $("#eventFormUpdate"),
url = $form.attr('action');
console.log('got vars');
$.post(url, $form.serialize()).done(function () {
console.log('am in');
$("#modal-closeUpdate").click();
console.log('posted');
});
});
});
$("#descUpdate")
.focus(function() {
if (this.value === this.defaultValue) {
this.value = '';
}
})
.blur(function() {
if (this.value === '') {
this.value = this.defaultValue;
}
});
Update
This is my controller
public function update(Request $request,$id)
{
$event = event::find($id);
$event->name = $request->name;
$event->description = $request->description;
$event->starting_date = $request->starting_date;
$event->ending_date = $request->ending_date;
$event->assigned_to = $request->assigned_to;
$event->save();
}
And this My routes call:
Route::patch('Event/{eventID}/Update', 'EventsController#update');
One last thing,at first the script was on my main page,and it didn't work so i tried to put it in in the called page with xmlhttprequest,and still doesn't work.
The only thing i can think of is,when i call the new page(the form to edit and update data) the script is already loaded in the main page,so it doesn't find the ids of the elements to handle,that's why it does not work,or at least this is the only reason i could find .
Any suggestions please?
Well first of all you have an error in your datepickers min and max,they don't match the field names you have set,set them to this
max: 'ending_dateUpdate'
min: 'starting_dateUpdate'
Second,the field names in your form,don't match those on your controller page,so it can't really update if it can't find the data,this should be your controller page:
public function update(Request $request,$id)
{
$event = event::find($id);
$event->name = $request->nameUpdate;
$event->description = $request->descriptionUpdate;
$event->starting_date = $request->starting_dateUpdate;
$event->ending_date = $request->ending_dateUpdate;
$event->assigned_to = $request->assigned_toUpdate;
$event->save();
}
Hope it helps .

bootstrapValidator Validating multiple inputs as one not working

On my login view. I am using bootstrap validator https://github.com/nghuuphuoc/bootstrapvalidator/tree/v0.5.2. For the php side of thing I use codeigniter MVC framework 3.0.3
I have to input fields called username and password and one hidden input field called user_info.
With bootstrap validator what I am tring to do is validate multple input fields as one.
But keep on getting this fire bug error below
Image
Here is my login form
<?php echo $header;?>
<?php echo form_open_multipart('admin/common/login', array('id' => 'login-form','role' => 'form'));?>
<div class="row" id="login-panel">
<div class="col-lg-offset-3 col-lg-6 col-md-offset-3 col-md-6 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title"><?php echo $heading_title;?></h1>
</div>
<div class="panel-body">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1"><i class="fa fa-user"></i></span>
<input type="text" name="username" class="form-control" value="" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon" id="basic-addon2"><i class="fa fa-lock"></i></span>
<input type="password" name="password" class="form-control" value="" placeholder="Password">
</div>
</div>
<input type="hidden" name="user_info" />
</div><!-- . panel-body -->
<div class="panel-footer">
<div class="text-right">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</div><!-- . panel-footer -->
</div><!-- . panel panel-default -->
</div>
</div><!-- # login-panel -->
<?php echo form_close();?>
<script type="text/javascript">
$(document).ready(function() {
$('#login-form')
.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
user_info: {
excluded: false,
validators: {
notEmpty: {
message: 'Please fill out each field'
}
}
}
}
})
.on('keyup', 'input[name="username"], input[name="password"]', function(e) {
var y = $('#login-form').find('[name="username"]').val(),
m = $('#login-form').find('[name="password"]').val(),
// Set the user_info field value
$('#login-form').find('[name="user_info"]').val(y === '' || m === '' ? '' : [y, m].join('.'));
// Revalidate it
$('#login-form').bootstrapValidator('revalidateField', 'user_info');
});
});
</script>
<?php echo $footer;?>
Question: How can I make bootstrap validator validate multiple input fields as one correctly?
Keep a ; instead of , here:
m = $('#login-form').find('[name="password"]').val(),
Script:
$(document).ready(function() {
$('#login-form')
.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
user_info: {
excluded: false,
validators: {
notEmpty: {
message: 'Please fill out each field'
}
}
}
}
})
.on('keyup', 'input[name="username"], input[name="password"]', function(e) {
var y = $('#login-form').find('[name="username"]').val(),
m = $('#login-form').find('[name="password"]').val(); //<= keep ; here
// Set the user_info field value
$('#login-form').find('[name="user_info"]').val(y === '' || m === '' ? '' : [y, m].join('.'));
// Revalidate it
$('#login-form').bootstrapValidator('revalidateField', 'user_info');
});
});
Here is what I get in their website . It uses the concept of adding a hidden field and combining data into the hidden field. Then we can validate the new hidden field like regular field.
Hope this helps.

form validation and submission

I am using formvalidation.io but I cannot stop the form submitting on successful validation. It immediately submits request and refreshes page. I need to send form information via ajax.
I must be overlooking something obvious?
http://jsfiddle.net/k281at67/94/
The HTML:
<form method="post" id="estimateForm1" class="form-horizontal bv-form">
<input type="hidden" name="page_source" id="page_source" value=""/>
<fieldset>
<input type="hidden" name="RefferingPage" value="' . $page . '" />
<div class="form-group">
<div class="row">
<div class="col-md-8 pad_right">
<input type="text" class="form-control" name="Name" placeholder="*Your name" value="" />
</div>
</div><!--row-->
</div><!--form group-->
<div class="form-group">
<div class="row">
<div class="col-md-8 pad_right">
<input type="text" class="form-control" name="Phone" placeholder="*Phone" class="phone" value="111-111-1111" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-8 pad_right">
<input type="text" name="Email" class="form-control" placeholder="*Email" id="" value="pie#aol.com"/>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-2 col-md-offset-5 col-xs-2">
<button class="btn btn-default" type="submit" disabled="disabled">
<i class="fa fa-eye"></i>
Validate
</button>
</div>
</div>
</div>
</fieldset>
</form>
The Javascript
jQuery('#estimateForm1')
.formValidation({
framework: 'bootstrap',
err: {
container: 'tooltip'
},
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
Name: {
row: '.col-md-8',
validators: {
notEmpty: {
message: 'The first name is required'
},
stringLength: {
min: 2,
message: 'Must be at-least 2 characters long.'
},
regexp:
{
message: 'Please only use A-Z characters.',
regexp: /^[a-zA-Z]+$/
}
}
},
Phone: {
row: '.col-md-8',
validators: {
notEmpty: {
message: 'The phone number is required'
},
stringLength: {
min: 14,
max: 15,
message: 'Not a valid phone #.'
},
regexp: {
message: 'The phone number can only contain the digits, spaces, -, (, ), + and .',
regexp: /^[0-9\s\-()+\.]+$/
}
}
},
Email: {
row: '.col-md-8',
validators: {
notEmpty: {
message: 'The email address is required'
},
regexp: {
regexp: '^[^#\\s]+#([^#\\s]+\\.)+[^#\\s]+$',
message: 'The value is not a valid email address'
}
}
}
}
}).find('[name="Phone"]').mask('(000) 000-0000')
.on('success.field.fv', function(e, data) {
if (data.fv.getSubmitButton()) {
e.preventDefault();
//data.fv.disableSubmitButtons(true);
console.log('prevented submission');
}
}).on('success.form.bv',function(e)
{
e.preventDefault();
console.log('prevented submission');
});
You have a typo in your code:
This =>
.on("success.form.bv", function(e) { ...
should be =>
.on("success.form.fv", function(e) { ...
You have to trigger the event on the form instance, not the Phone field.
I suggest you to do the following:
jQuery('#estimateForm1')
.find('[name="Phone"]')
.mask('(000) 000-0000')
.end() // <=== DON'T FORGOT TO ADD THIS
.formValidation({
// ...
})
.on('success.field.fv', function(e, data) {
// ...
})
.on('success.form.fv',function(e) {
e.preventDefault();
console.log('prevented submission');
});
See Using Ajax to submit the form example.
Try this
.on('success.form.bv',function(e)
{
e.preventDefault();
return false;
console.log('prevented submission');
});
This function to stop call submit event. It should be calling manual
$(document).ready(function() {
$("#formname").submit(function(e) {
e.preventDefault();
});
});
Second option should be good for validation of form to client side. If you validate all value to return true then fire submit event other wise not fire.
function validation() {
return false;
});
But calling function on submit button like this
onclick="return validation()

jquery validation plugin ajax submit a form not working

I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is working but ajax code will do two time and the form cannot send out.
bootstrap form
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic</label>
<input class="form-control" type="text" name="topic" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label "> ruser: </label>
<input class="form-control" type="text" name="ruser" value="<?php echo $username; ?>" readonly/>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
<button class="btn btn-success" id="submitcontact">ok</button>
</form>
javascript
$(document).ready(function () {
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages: {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter nuser'
},
content: {
required: 'enter content'
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function (msg) {
alert("ok!");
if (msg == 'ok') {
alert(msg);
location.reload()
}
},
error: function () {
alert("failure");
}
});
return false;
}
});
$('#submitcontact').click(function () {
$('form.contact').submit();
})
});
How can i fix the problem?
The jsfiddle
You probably need to remove this bit:
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Please see the example:
http://jsfiddle.net/8eoreedb/1/
Use .valid() method:
Description: Checks whether the selected form is valid or whether all selected elements are valid.
Updated Fiddle
$('#submitcontact').on('click', function() {
if ($('form.contact').valid()) {
// Form is valid
$('form.contact').submit();
}
});
Doc: http://jqueryvalidation.org/valid/
Demo: http://jsfiddle.net/8eoreedb/4/

Enable stripe button upon bootstrap validation

I wanted to use BootstrapValidator to validate couple of fields and enable stripe button upon validation. The problem is that the button is enabled once any of the fields are validated. I am trying to enabled the stripe button once both fields are validated.(ignore the datepicker field). below is my javascript code.
$('#myform')
.bootstrapValidator({
message: 'This value is not valid',
//live: 'submitted',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fname: {
message: 'The first name is not valid',
validators: {
notEmpty: {
message: 'The first name is required and can\'t be empty'
},
stringLength: {
min: 2,
max: 30,
message: 'The first name must be more than 6 and less than 30 characters long'
},
/*remote: {
url: 'remote.php',
message: 'The username is not available'
},*/
regexp: {
regexp: /^[a-zA-Z]+$/,
message: 'The first name can only consist of alphabetical letters'
}
}
},
lname: {
message: 'The last name is not valid',
validators: {
notEmpty: {
message: 'The last name is required and can\'t be empty'
},
stringLength: {
min: 3,
max: 30,
message: 'The last name must be more than 6 and less than 30 characters long'
},
/*remote: {
url: 'remote.php',
message: 'The username is not available'
},*/
regexp: {
regexp: /^[a-zA-Z]+$/,
message: 'The last name can only consist of alphabetical letters'
}
}
},
}
})
.on('success.form.fv', function(e) {
// Prevent submit form
e.preventDefault();
var $form = $(e.target),
validator = $form.data('bootstrapValidator');
$form.find('#result').html('Thanks for signing up. Now you can sign in as ' + validator.getFieldElements('fname').val()).show();
});
$('.stripe-button-el').attr("disabled", true );
});
And this is the form:
<form id="myform" method="post" class="form-horizontal">
<div class="form-group" >
<label class="col-sm-3 control-label">Full name</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="fname" placeholder="First name" id="fname" />
</div>
<div class="col-sm-4">
<input type="text" class="form-control" name="lname" placeholder="Last name" id="lname" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Pick a Date</label>
<div class="col-sm-4">
<input class="form-control" name="date" type="text" id="datepicker"/>
</div>
<div class="col-sm-4">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<?php echo $stripe['publishable_key']; ?>"
data-amount="5000" data-zip-code = "true" data-description="Whatever">
</script>
</div>
</div>
<div class="form-group" >
<label class="col-sm-4 control-label" id='results'></label>
</div>
</form>
You need an event triggered with every keystroke to determine whether the form is valid. Once you know its valid, you can take action on the button. BootstrapValidator's API includes everything you need to do this (other than capturing the event itself).
You can append this on method to your $('#myform') chain:
.on('keyup', function() {
// Get your form's validator
var validator = $('#myform').data('bootstrapValidator');
// Validate the form
validator.validate();
// Check if the form is valid
if (validator.isValid()) {
// Perform action on Stripe button
}
});

Categories

Resources