Submit handler is working but its very slow - javascript

Hello guys I am submitting my form using submit handler and its working but its very slow. Please help me to make it fast. Thanks in advance
Following is my javascript code for login form......
var handleLoginForm = function () {
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
username: {
required: true
},
password: {
required: true
},
user_type: {
required: true
},
remember: {
required: false
}
},
messages: {
username: {
required: "Username is required."
},
password: {
required: "Password is required."
},
user_type: {
required: "User Type is Required."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
data: $('#form_modulesadd').serialize(),
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
$( ".login-form input" ).submit();
window.location.href = "check.php";
}
});
It was fast when i was submitting the form using php but I must have to use javascript to submit this form......

Run the JS when the form is submitted:
$(".login-form").submit(function(){
$('.login-form').validate({
errorElement: 'label', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
username: {
required: true
},
password: {
required: true
},
user_type: {
required: true
},
remember: {
required: false
}
},
messages: {
username: {
required: "Username is required."
},
password: {
required: "Password is required."
},
user_type: {
required: "User Type is Required."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-error', $('.login-form')).show();
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.control-group').addClass('error'); // set error class to the control group
},
data: $('#form_modulesadd').serialize(),
success: function (label) {
label.closest('.control-group').removeClass('error');
label.remove();
},
errorPlacement: function (error, element) {
error.addClass('help-small no-left-padding').insertAfter(element.closest('.input-icon'));
},
submitHandler: function (form) {
$( ".login-form input" ).submit();
window.location.href = "check.php";
}
});
});
This keeps the JS from running until the form is submitted.
UPDATE:
$(".login_form").submit(function(){
$(this).validate({ ... });
});
Not sure if this will work, but the repeated selector seemed a bit awkward to me.

I solved the same problem by changing the implementation of submitHandler like below. I just take the first item [0] of the forms selector.
submitHandler: function (form) {
$(".login-form input")[0].submit();
...
}

Related

How change JQuery Validation Message without refreshing website [duplicate]

This question already has answers here:
jquery .validate() variable error message
(3 answers)
Closed 1 year ago.
I am using jQuery Validation from here: https://jqueryvalidation.org. Currently, I have two types of Messages prepared. They are popping out. When I'm changing language on web variables global variable with messages also is changing, but message in validator don't. Language of the validator change after I refresh the website. How can I change it on live without refreshing the website?
HTML is no needed, because everything is happening in JS file.
This is a function that are changing values in the object.
JS:
function setLang(lang) {
(lang) ? lang: "pol";
if (lang == "pol") {
Messages = {
formFirstnameRequired: 'Pole imie jest wymagane!',
formLastnameRequired: 'Pole nazwisko jest wymangane!',
formEmailRequired: 'Pole email jest wymagane!',
formTitleRequired: 'Pole Tytuł jest wymagane!',
formMessageRequired: 'Pole wiadomość jest wymagane!',
}
} else if (lang == "eng") {
Messages = {
formFirstnameRequired: 'Field firstname is required!',
formLastnameRequired: 'Field lastname is required!',
formEmailRequired: 'Field email is required!',
formTitleRequired: 'Field title is required!',
formMessageRequired: 'Field message is required!',
}
}
}
I'm also using this cookie for managing the language of this form validation:
if (getCookie("lang") == null) {
document.cookie = 'lang=pol';
}
setLang(getCookie("lang"));
$(".nav").on("click", "#polLang", (event) => {
document.cookie = 'lang=pol';
setLang(getCookie("lang"));
});
$(".nav").on("click", "#engLang", (event) => {
document.cookie = 'lang=eng';
setLang(getCookie("lang"));
});
Here I have validation
JS:
$("#contactForm").validate({
rules: {
"formFirstname": {
required: true,
},
"formLastname": {
required: true,
},
"formEmail": {
required: true,
},
"formTitle": {
required: true,
},
"formMessage": {
required: true,
}
},
messages: {
"formFirstname": {
required: Messages.formFirstnameRequired,
string: true
},
"formLastname": {
required: Messages.formLastnameRequired,
string: true
},
"formEmail": {
required: Messages.formEmailRequired,
email: true,
},
"formTitle": {
required: Messages.formTitleRequired,
string: true
},
"formMessage": {
required: Messages.formMessageRequired,
string: true
}
},
onfocusout: false,
errorPlacement: function(error) {
toastr.error(error);
},
submitHandler: function(form) {
toastr.success('success')
return false;
},
invalidHandler: function() {
return;
}
});
Jquery validator msgs are static. If you want to update them dynamically you can create a function, that will return a new msg.
Like this:
"formFirstname": {
required: function getFormFirstname() { return Messages.formFirstnameRequired },
string: true
},

Submit form data without javascript

TL;DR
How to make a form to make a normal post instead of making a submission via JQuery?
I bought a theme recently and I'm making a form with several steps. I'm using the "Wizard" component of this theme and you can see how it works through this link:
https://keenthemes.com/metronic/preview/demo1/custom/pages/wizard/wizard-2.html
My problem is with the submission of this form. I would like to make a common submission. As it stands, the form must be submitted using JQuery.
I made some changes to my form to be able to make a common submission. For example:
I informed the POST method and an action for the form:
<form class="m-form m-form--label-align-right- m-form--state-" id="m_form" action="sale/new" method="post" enctype="multipart/form-data">
And I also created a "Submit" button:
<button type="submit" class="btn btn-primary" data-wizard-action="submit">Save</button>
For the Wizard work, the form must have an id (m_form) and the submit button must also have the attribute data-wizard-action="submit".
I am using the javascript of the theme itself, and it is precisely because I don't know much about JS that I believe I am facing problems. I tried to remove the e.preventDefault, but the form still does not POST to the action I determined. The javascript code for the theme I'm using is this:
//== Class definition
var WizardDemo = function () {
//== Base elements
var wizardEl = $('#m_wizard');
var formEl = $('#m_form');
var validator;
var wizard;
//== Private functions
var initWizard = function () {
//== Initialize form wizard
wizard = new mWizard('m_wizard', {
startStep: 1
});
//== Validation before going to next page
wizard.on('beforeNext', function(wizardObj) {
if (validator.form() !== true) {
wizardObj.stop(); // don't go to the next step
}
})
//== Change event
wizard.on('change', function(wizard) {
mUtil.scrollTop();
});
//== Change event
wizard.on('change', function(wizard) {
if (wizard.getStep() === 1) {
// alert(1);
}
});
}
var initValidation = function() {
validator = formEl.validate({
//== Validate only visible fields
ignore: ":hidden",
//== Validation rules
rules: {
//=== Client Information(step 1)
//== Client details
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUS: true
},
//== Mailing address
address1: {
required: true
},
city: {
required: true
},
state: {
required: true
},
city: {
required: true
},
country: {
required: true
},
//=== Client Information(step 2)
//== Account Details
account_url: {
required: true,
url: true
},
account_username: {
required: true,
minlength: 4
},
account_password: {
required: true,
minlength: 6
},
//== Client Settings
account_group: {
required: true
},
'account_communication[]': {
required: true
},
//=== Client Information(step 3)
//== Billing Information
billing_card_name: {
required: true
},
billing_card_number: {
required: true,
creditcard: true
},
billing_card_exp_month: {
required: true
},
billing_card_exp_year: {
required: true
},
billing_card_cvv: {
required: true,
minlength: 2,
maxlength: 3
},
//== Billing Address
billing_address_1: {
required: true
},
billing_address_2: {
},
billing_city: {
required: true
},
billing_state: {
required: true
},
billing_zip: {
required: true,
number: true
},
billing_delivery: {
required: true
},
//=== Confirmation(step 4)
accept: {
required: true
}
},
//== Validation messages
messages: {
'account_communication[]': {
required: 'You must select at least one communication option'
},
accept: {
required: "You must accept the Terms and Conditions agreement!"
}
},
//== Display error
invalidHandler: function(event, validator) {
mUtil.scrollTop();
swal({
"title": "",
"text": "There are some errors in your submission. Please correct them.",
"type": "error",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
},
//== Submit valid form
submitHandler: function (form) {
}
});
}
var initSubmit = function() {
var btn = formEl.find('[data-wizard-action="submit"]');
btn.on('click', function(e) {
e.preventDefault();
if (validator.form()) {
//== See: src\js\framework\base\app.js
mApp.progress(btn);
//mApp.block(formEl);
//== See: http://malsup.com/jquery/form/#ajaxSubmit
formEl.ajaxSubmit({
success: function() {
mApp.unprogress(btn);
//mApp.unblock(formEl);
swal({
"title": "",
"text": "The application has been successfully submitted!",
"type": "success",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
}
});
}
});
}
return {
// public functions
init: function() {
wizardEl = $('#m_wizard');
formEl = $('#m_form');
initWizard();
initValidation();
initSubmit();
}
};
}();
jQuery(document).ready(function() {
WizardDemo.init();
});
I would like to know if there is any way to keep the Wizard and the validation working, but in a way that it is possible to make a common submission for the action that I defined for the form.
You just need a slight change in your initSubmit() function.
var initSubmit = function() {
var btn = formEl.find('[data-wizard-action="submit"]');
btn.on('click', function(e) {
e.preventDefault();
if (validator.form()) {
//== See: src\js\framework\base\app.js
mApp.progress(btn);
//mApp.block(formEl);
//== See: http://malsup.com/jquery/form/#ajaxSubmit
/*
formEl.ajaxSubmit({
success: function() {
mApp.unprogress(btn);
//mApp.unblock(formEl);
swal({
"title": "",
"text": "The application has been successfully submitted!",
"type": "success",
"confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
});
}
});
*/
// Use this one instead:
formEl.submit();
}
});
}
This simply means that:
Instead of doing an AJAX request if validation result is positive, just do a normal submission.
Here's the reference for the submit() method of jQuery:
https://api.jquery.com/submit/
By the way, this question can be found under the title (how to submit form using jQuery ?), see this question for example:
Submit a form using jQuery

jquery choosen select validation messages are not dis-appering untill the form submit

jQuery chosen select validation messages are not disappearing until the form submit. I applied required validation if I submit the form without choosing the value error message is displaying. But after I choose it is not disappearing as normal select boxes, it is staying until the form submit.
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" });
$("#postJob").validate({
rules: {
skills:{
required:true,
},
});
please provide a running code snippets to understand the problem more easily.
jQuery validate messages are disappeared once the validation is fulfilled.
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5
},
"email": {
required: true,
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
Here is the fiddle:
http://jsfiddle.net/amwmedia/sw87W/

How to have an alert and document.getElementById().focus() in ajax?

How do I have these alert('Please input your firstname.'); document.getElementById ("firstname").focus(); inside my ajax code where the error message shows? Because I have it in text in my webpage but I want it to be an alert and focus on the input id like the one javascript. How do I do it here?
<script type="text/javascript">
$('document').ready(function()
{
$("#register-form").validate({
rules:
{
firstname: {
required: true
},
lastname: {
required: true
},
},
messages:
{
firstname:"Please input your firstname.",
lastname:"Please input your lastname.",
},
submitHandler: submitForm
});
});
</script>

errorClass in jquery validate plugin?

I am using jquery validate plugin in my web application to validate forms for blank and other simple validations.
I am using below code to setup jquery validate plugin for my form, there is a erroClass option in it, where I have defined a CSS class name authError which I want to apply on error messages, but its applying the same class to INPUT box as well, I don't want to apply it in INPUT box, just want it for error message. Please check and help. Thanks!
$("#frmSignin").validate({
debug: false,
errorClass: "authError",
errorElement: "span",
rules: {
username: {
required: true,
minlength: 10
},
password: {
required: true
}
},
messages: {
username: {
required: "Please enter your username"
},
password: {
required: "Please enter your password"
}
}
});
Thanks, for the tricks guys, but I instead found a better way by using the jQuery code only. There is a highlight event in validate plugin which is called when error occurred to highlight the error fields, I just removed the class form element when this event is called.
$("#frmSignin").validate({
debug: false,
errorClass: "authError",
errorElement: "span",
rules: {
username: {
required: true,
minlength: 10
},
password: {
required: true
}
},
messages: {
username: {
required: "Please enter your username"
},
password: {
required: "Please enter your password"
}
},
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
}
});
You should actually be just defining different classes for input and span (span since errorElement is set to span, otherwise it will be label), rather than removing the applied class
e.g.
span.authError {color:red;}
input.authError {border:1px dotted red;}
and not just .authError{} which will get applied to both input and span
$("#borrowerForm").validate({
errorElement: 'span',
errorElementClass: 'input-validation-error',
errorClass: 'field-validation-error',
errorPlacement: function(error, element) {},
highlight: function(element, errorClass, validClass) {
$(element).addClass(this.settings.errorElementClass).removeClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(this.settings.errorElementClass).removeClass(errorClass);
},
onkeyup: false,
errorPlacement: function (error, element) { error.insertAfter(element); }
});
In the jQuery validation plugin, the errorClass is both applied to the error message element (usually a <label>, but a <span> in your case) and to the validated element itself. Since you only want to style the error message element, you should write:
span.authError {
// Your error element style.
}
If you want to give css for the error message.
Then in place of using errorClass define css rule
label.error
Check this:
jQuery.validator.messages.required = "";
$('#frm-contact').validate({
invalidHandler: function (e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted below'
: 'You missed ' + errors + ' fields. They have been highlighted below';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
},
onkeyup: false,
submitHandler: function () {
$("div.error").hide();
alert("submit! use link below to go to the other step");
},
highlight: function (element, required) {
$(element).fadeOut(function () {
$(element).fadeIn();
$(element).css('border', '2px solid #FDADAF');
});
},
unhighlight: function (element, errorClass, validClass) {
$(element).css('border', '1px solid #CCC');
}
});

Categories

Resources