How to make Ajax call after successfully filled the form fields - javascript

Here I am using jQuery validation. It is working fine, after fill all form fields I want do Ajax call but I am not able to do that. I am getting error. How can I do?
jQuery(document).ready(function(){
jQuery("#SubmitForm").validate({
rules: {
"address": {
required: true
},
"username": {
required: true
},
"mobileNumber": {
required: true,
number: true,
minlength : 12
},
"userEmailid": {
required: true,
email: true
},
"message": {
required: true
}
},
messages: {
"address": {
required: "Please enter your Location."
},
"username": {
required: "Please enter your Fullname."
},
"mobileNumber": {
required: "Please enter your Mobile Number."
},
"userEmailid": {
required: "Please enter your Email.",
email: "Please enter valid Email."
},
"message": {
required: "Please enter Message."
}
},
/* jQuery.ajax({
type:'POST',
url :"php/submit_hitachiForm.php",
data: jQuery('form#SubmitForm').serialize(),
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "success"){
$("#success_message").show();
$("#success_message").fadeOut(4000);
}
},
error:function(exception){
alert('Exeption:'+exception);
}
}); */
});
});

Put all the validation:
$('#SubmitForm).validate({
// validation rules
});
and after that initialize the validation function like:
if($('#SubmitForm).valid())
{
// make ajax() call here
}

Try this in your code
submitHandler: function() {
/*ajax request*/
}

Related

jQuery Validate not acting on custom validation value

TLDR version: I have a custom jquery validation the returns the correct values but the rule is not getting enforced.
I have a custom validation rule that looks like this:
$.validator.addMethod("isDomainValid", function(value, element) {
var domain = value.split("#");
$.get('/api/validate-domain/' + domain[1], function(data, status) {
domain = JSON.parse(data);
console.log(domain['status'] === 'valid');
return (domain['status'] === 'valid');
});
});
This validation calls a PHP API that checks if the email's domain name is live, hence correct. This API returns the correct values and the console.log() also reflects the correct values, which is the value I am returning as a boolean. All good so far...
I call this validation rule like this:
validator.validate({
rules: {
email: {
required: true,
email: true,
isDomainValid: true,
},
});
I also have some custom error messages (I think maybe irrelevant) like the following:
messages: {
email: {
required: "The Email Address cannot be empty",
isDomainValid: "Please correct the Email Address after the # character",
email: "Invalid Email Address format",
}, },
All my validations, including one other custom validation work flawlessly except this one. Here is all the code I am running in case someone wants to see the whole thing. Again, all validations work except the custom isDomainValid validation.
var validator = $('#checkout_form');
$.validator.addMethod("checkPoBox", function(value, element) {
let cleansedValue = $.trim(value.toLowerCase()).replace(/[^a-zA-Z]+/g, '');
let checked = $('#ship-box').prop('checked') ? true : false;
if (/pobox/i.test(cleansedValue) && checked && element.name == 'shipping_address') {
return false;
}
if (/pobox/i.test(cleansedValue) && !checked && element.name == 'billing_address') {
return false;
}
return true;
});
$.validator.addMethod("isDomainValid", function(value, element) {
var domain = value.split("#");
$.get('/api/validate-domain/' + domain[1], function(data, status) {
domain = JSON.parse(data);
console.log(domain['status'] === 'valid');
return (domain['status'] === 'valid');
});
});
validator.validate({
rules: {
email: {
required: true,
email: true,
isDomainValid: true,
},
billing_first_name: {
required: true
},
billing_last_name: {
required: true
},
billing_address: {
required: true,
checkPoBox: true
},
billing_city: {
required: true
},
billing_state: {
required: true
},
billing_zip: {
required: true,
minlength: 5,
maxlength: 5,
digits: true
},
billing_phone: {
required: true,
minlength: 10,
maxlength: 10,
digits: true
},
name_on_credit_card: {
required: true
},
credit_card_number: {
required: true,
creditcard: true
},
expiration_month: {
required: true
},
expiration_year: {
required: true
},
cvv: {
required: true,
minlength: 3,
maxlength: 4,
digits: true
},
shipping_first_name: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_last_name: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_address: {
required: function () {
return $('#ship-box').prop('checked');
},
checkPoBox: true
},
shipping_city: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_state: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_zip: {
required: function () {
return $('#ship-box').prop('checked');
},
minlength: 5,
maxlength: 5,
digits: true
},
shipping_phone: {
required: function () {
return $('#ship-box').prop('checked');
},
minlength: 10,
maxlength: 10,
digits: true
}
},
messages: {
email: {
required: "The Email Address cannot be empty",
isDomainValid: "Please correct the Email Address after the # character",
email: "Invalid Email Address format",
},
billing_first_name: "First Name cannot be blank",
billing_last_name: "Last Name cannot be blank",
billing_address: {
required: "Address cannot be blank",
checkPoBox: "Products cannot be shipped to a P.O. Box"
},
billing_city: "Town/City cannot be blank",
billing_state: "Please select a State",
billing_zip: "Please enter a valid 5 digit Zip Code",
billing_phone: "Please enter a valid 10 digit Phone Number",
name_on_credit_card: "Name on Card cannot be blank",
credit_card_number: "Please enter a valid Credit Car Number",
expiration_month: "Please select an Expiration Month",
expiration_year: "Please select an Expiration Year",
cvv: "Please enter a valid 3 or 4 digit CVV",
shipping_first_name: "First Name cannot be blank",
shipping_last_name: "Last Name cannot be blank",
shipping_address: {
required: "Address cannot be blank",
checkPoBox: "Products cannot be shipped to a P.O. Box"
},
shipping_city: "City cannot be blank",
shipping_state: "Please select a State",
shipping_zip: "Please enter a valid 5 digit Zip Code",
shipping_phone: "Please enter a valid 10 digit Phone Number",
},
invalidHandler: function(event, validator) {
if(validator.numberOfInvalids() > 0) {
event.preventDefault();
$('button#place_order_btn').text("PLACE ORDER");
return false;
}
},
submitHandler: function (validator) {
validator.submit();
}
});
Any help will be greatly appreciated.
I think you're running into a problem where the return value for the success callback function is lost in the $.get method. In my experience I've had to trigger errors manually as part of the callback when checking against the server in a similar way.
Alternatively, I was digging around and found some jQuery Validation documentation that seems like it would make what you are trying to do a little easier: https://jqueryvalidation.org/remote-method/
Try updating the rules.email properties, replacing isDomainValid:
rules: {
email: {
required: true,
email: true,
remote: {
url: function() {
var value = $("[name='email']").val();
var domain = value.split("#");
return "/api/validate-domain/" + domain[1];
},
}
},
You can remove the call to $.validator.addMethod that registers the "isDomainValid" method.
Also, don't forget to update isDomainValid elsewhere, replacing it with remote so the messages are correct.
messages: {
email: {
required: "The Email Address cannot be empty",
email: "Invalid Email Address format",
remote: "Please correct the Email Address after the # character",
},

How to create a validation plugin for web application using javascript/jquery?

I am trying to create a validation plugin for web application which evaluates the form when only the form-id is passed to the plugin using javascript/jquery
This is the code i have written where i have used the name of each field to evaluate the input for the html page
$(document).ready(function () {
$('#formId').validate({
rules: {
'Name': {
required: true,
minlength: 3
},
'Email': {
required: true,
minlength: 5
},
'password': "required",
'Confirm_password': {
required : true,
equalTo: "#password"
},
'test': {
required: true
},
'Radio': { required: true },
'ddl': {
required: {
depends: function (element) {
if ('none' == $('#select_field').val()) {
$('#select_field').val('');
}
return true;
}
}
}
},
messages: {
'Name': {
required: "Enter the name",
minlength: "The name should be atleast of 3 characters "
},
'Email': {
required: "Enter the emailid",
minlength: "The emailid should be atleast of 5 characters"
},
'test': {
required: "Check atleast one box"
},
'Radio':
{
required:"Please select an option<br/>"
},
'ddl':
{
required: "Please select an option from the list"
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
});
Use the Jquery Validation plugin.
Read this

jquery validation is not running with Ajax

Why validation is not working in this script ?
I gave blank input but it is not giving the required messsage and also regx is not working.
$(document).ready(function(){
var $form = $(this);
$.validator.addMethod("regx", function(value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid Pan number.");
$("#checkval").validate({ //here is form id #checkval
showErrors: function(errorMap, errorList) {
for (var error in errorMap) {
$.growl.error({ message: errorMap[error] });
}
},
onkeyup: false,
rules: {
oldemail: {
required: true,
regx: /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/
},
newemail: {
required: true,
regx: /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/
}
},
messages: {
oldemail: {
required: "Please enter old e-mail ",
regx: "Please enter your valid e-mail address"
},
newemail: {
required: "Please enter new e-mail ",
regx: "Please enter your valid e-mail address"
}
},
// From here started ajax code.
submitHandler: function(form) {
$.ajax({
url: index.php?act=account,
type: "POST",
data: $(form).serialize(),
success: function(response) {
alert(response);
$('#inquiryFormHolder').html("Your form was submitted!");
// here is div id #inquiryFormHolder
}
});
$form.submit();
}
});
});

JS Validate - valid input & loagin bar while remote

I'm making a simple javascript form with validation. I've already planned my sintax and everything but I need help with two things:
I've templating my JS to output the error, but how can I change the inputbox color to "green" for example if the input is OK by validation?
My templating error until now:
$.validator.setDefaults(
{
showErrors: function(map, list)
{
this.currentElements.parents('label:first, .controls:first').find('.error').remove();
this.currentElements.parents('.control-group:first').removeClass('error');
$.each(list, function(index, error)
{
var ee = $(error.element);
var eep = ee.parents('label:first').length ? ee.parents('label:first') : ee.parents('.controls:first');
ee.parents('.control-group:first').addClass('error');
eep.find('.error').remove();
eep.append('<p class="error help-block"><span class="help-block error">' + error.message + '</span></p>');
});
//refreshScrollers();
}
});
Can you help me inserting the function to change the color if it's OK? I just can't figure it out.
Other thing is about showing a "loading" image while javascript is remotly checking if the user / email exists. I have everything ready and work, but I can't and don't know how to show a loading image while it checks ( before give error result ), neither tells the result is OK ( only in those fields ). My remote function:
$(function()
{
// validate signup form on keyup and submit
$("#registerform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 3,
remote:{
url: "inc/core/check_user.php",
type: "post",
data: {
username: function(){
return $( "#username" ).val();
}
}
}
},
password: {
required: true,
minlength: 5
},
confpassword: {
required: true,
minlength: 5,
equalTo: "#password"
},
scode: {
required: true,
minlength: 4,
maxlength: 6,
digits: true
},
scodeconf: {
required: true,
minlength: 4,
maxlength: 6,
digits: true,
equalTo: "#scode"
},
email: {
required: true,
email: true,
remote:{
url: "inc/core/check_email.php",
type: "post",
data: {
email: function(){
return $( "#email" ).val();
}
}
}
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required",
address: "required",
zipcode: "required",
city: "required",
state: "required",
country: "required",
data: "required",
age: "required"
},
messages: {
firstname: $lang['register_jquery_pnome'],
lastname: $lang['register_jquery_unome'],
username: {
required: $lang['register_jquery_username'],
minlength: $lang['register_jquery_username_min'],
remote: $lang['register_jquery_username_registado'],
},
password: {
required: $lang['register_jquery_password'],
minlength: $lang['register_jquery_password_min']
},
confpassword: {
required: $lang['register_jquery_password'],
minlength: $lang['register_jquery_password_min'],
equalTo: $lang['register_jquery_password_equalto']
},
email:{
required: $lang['register_jquery_email_valido'],
remote: $lang['register_jquery_email_registado']
},
agree: $lang['register_jquery_tos'],
address: $lang['register_jquery_morada'],
zipcode: $lang['register_jquery_zipcode'],
city: $lang['register_jquery_city'],
state: $lang['register_jquery_state'],
country: $lang['register_jquery_pais'],
data: $lang['register_jquery_data'],
age: $lang['register_jquery_age'],
scode: {
required: $lang['register_jquery_codigoseguranca'],
minlength: $lang['register_jquery_codigoseguranca_min'],
maxlenght: $lang['register_jquery_codigoseguranca_max'],
digits: $lang['register_jquery_codigoseguranca_digits']
},
scodeconf: {
required: $lang['register_jquery_codigoseguranca'],
minlength: $lang['register_jquery_codigoseguranca_min'],
maxlenght: $lang['register_jquery_codigoseguranca_max'],
digits: $lang['register_jquery_codigoseguranca_digits'],
equalTo: $lang['register_jquery_codigoseguranca_equalto']
},
}
});
});
Could someone help me with those two things? Thanks in advance!
For changing the color of valid elements you can add a class to them by adding the following to your validate function:
$("#registerform").validate({
validClass: "success",
// your code
});
Then style your success class: .success {background-color: green}
The remote option is just a normal jQuery.ajax() call so you can use all the same settings.
Should be something like this:
remote:{
url: "inc/core/check_user.php",
beforeSend: function( xhr ) {
//your code to show a message
},
type: "post",
data: {
username: function(){
return $( "#username" ).val();
}
},
complete: function() {
// your code to hide the message
}
}

Remote validation

below is my code the validation only works without the remote validation. once i include remote validation, it submit the form without completing all the other form validations?
$(document).ready(function() {
$("#form1").validate({
rules: {
firstName: "required",// simple rule, converted to {required:true}
lastName: "required",
email: {// compound rule
required: true,
email: true,
success: "valid",
remote: "checkAddress.php"
},
password: {
required: true,
success: "valid",
minlength: 5
},
verify: {
required: true,
success: "valid",
minlength: 5,
equalTo: "#password"
},
address1: "required",
city: "required",
province: "required",
dob: {
required: true,
date: true,
success: "valid"
},
captcha_code: {
required: true,
captcha_code: true,
remote: "checkCaptcha.php"
}
},
messages: {
email:{
remote: "This email is already registered! One registration per email address."
},
captcha_code:{
remote: "Enter the right captcha value!."
}
},
onsubmit: true
});
});
What I was asking was if you have implemented captcha_code as a method? in captcha_code: true,.
captcha_code: {
required: true,
captcha_code: true,
remote: "checkCaptcha.php"
}
Like this
jQuery.validator.addMethod("captcha_code", function(value, element) {
return (this.optional(element) || /* do something */ );
}, "");
I found this captcha demo and it has no captcha_code as method, only required and remote. So I was thinking if you have implemented it.
Here is the script from the demo. http://jquery.bassistance.de/validate/demo/captcha/
$(function(){
$("#refreshimg").click(function(){
$.post('newsession.php');
$("#captchaimage").load('image_req.php');
return false;
});
$("#captchaform").validate({
rules: {
captcha: {
required: true,
remote: "process.php"
}
},
messages: {
captcha: "Correct captcha is required. Click the captcha to generate a new one"
},
submitHandler: function() {
alert("Correct captcha!");
},
success: function(label) {
label.addClass("valid").text("Valid captcha!")
},
onkeyup: false
});
});
The remote URL is hit passing in the value of the field to which it’s expecting a JSON TRUE/FALSE in return, are you in this one?
so i changed:
email: {// compound rule
required: true,
email: true,
success: "valid",
remote: "checkAddress.php"
},
captcha_code: {
required: true,
captcha_code: true,
remote: "checkCaptcha.php"
}
to
email: {// compound rule
required: true,
remote: "checkAddress.php"
},
captcha_code: {
required: true,
remote: "checkCaptcha.php"
}
it works great, wow, you guys rock!!!

Categories