Form validation not working before submit with ajax method - javascript

I creating submit form with ajax but, i cant validate form before submit..
iam using codeigniter 3 with jquery validate
my code working, but i need set form like min lenghth, email format etc
this my code before (with input class="required")
$(document).ready(function(){
$(".save_post").click(function(){
if ($("#post_val").valid()) {
$("#post_val").submit();
}else{
return false;
}
var data = $('.post_form').serialize();
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/post_ajx/update_post",
data: data,
success: function(data) {
alert("Post Success!");
}
});
});
});
i trying to modified that code to this, but code its not working
$(document).ready(function(){
$(".save_post").click(function(){
$('#post_val').validate({
rules: {
title: {
required: true,
minlength: 10
},
image: {
required: true,
minlength: 5
}
},
messages: {
title:{
required: 'title error',
minlength: 'kurang dari 10'
},
image: {
required: true,
minlength: 5
}
}
});
var data = $('.post_form').serialize();
$.ajax({
type: 'POST',
url: "<?= base_url() ?>admin_ajx/post_ajx/update_post",
data: data,
success: function(data) {
alert("Post Success!");
}
});
});
});
my form like this
<form action="<?= base_url() ?>admin/add-post" method="POST" role="form" class="post_form" id="post_val">
<input type="text" name="title" class="form-control" placeholder="Title" id="post_title" onkeyup="auto_alias();">
<input class="form-control input-sm required" type="text" name="image" id="img_url" readonly="readonly" onclick="openKCFinder(this)" style="cursor:pointer" />
<a class="btn btn-sm btn-info save_post" onClick="CKupdate();$('#article-form').ajaxSubmit();">POST</a>
</form>
i expect, i can validate that form before submit

You are using jquery validate in an incorrect manner.
For starters you don't nest validate in a click event, and then you don't run your submit code independently. Instead you run it in the submit callback of validate.
A sample looks like this:
$("#ajax-contact-form").validate({
errorClass: "text-danger",
rules: {
name: {
required: true,
},
phone: {
required: false,
digits: true,
minlength: 7,
},
email: {
required: true,
email: true,
},
message: {
required: true,
minlength: 10,
},
},
submitHandler: function (form, e) {
e.preventDefault(); // important to prevent issues!!!
$("#contact-button").html('Sending...');
var str = $(form).serialize(); // to get your serialized form
$.ajax({
type: "POST",
url: base_path + "/contact/send",
data: str,
dataType: 'json',
success: function (data) {
var result = '';
if (data.status === 'success') {
$(form).trigger('reset');
result = '<div class="alert alert-success"><i class="fa fa-check"></i> ' + data.msg + '</div>';
} else {
result = '<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + data.msg + '</div>';
}
$("#contact-button").html('Send Message');
$('#note').html(result);
setTimeout(function () {
$("#note").fadeOut();
}, 8000);
}
});
},
});
also I would remove $('#article-form').ajaxSubmit(); from this onClick="CKupdate();$('#article-form').ajaxSubmit();". It holds no reference to current code, and it won't work with validate.

Related

How can I send ajax call after validation is correct?

I am trying to send data to my heroku database, i have user input from a html file and sending it through to my jquery file, my validation works but i wish to send my ajax call after this is valid, i.e. upon the submit button clicked. It doesn't seem to get to my ajax call( the ajax works).The success bit is my attempt to show success message (swal is sweetalert library & and not sure is success works). I believe my submit handler is at fault.
// * html code of form *
<form action="" name="registration"><br>
<label for="email">Email</label><br>
<input type="email" name="email" id="email" placeholder="example#example.com" /><br><br>
<label for="password">Password</label><br>
<input type="password" name="password" id="password"
placeholder="●●●●●" /><br><br>
<label for="repassword">Re-Type Password</label><br>
<input type="password" name="repassword" id="repassword"
placeholder="●●●●●" /><br><br>
<input type="checkbox" name="agreeBox" id="agreeBox" />
<label for="agree-boxId">I agree
to all statements in <a href="../documents/terms_of_service" class="term-service">Terms of
Service</a></label><br><br>
<button type="submit" id="signUp">Register</button>
<div class="signup-image">
<figure><img src="images/signup-image.png" alt="sign up image"></figure>
</div>
</form>
// ***** my content in Jquery file ******
$("form[name='registration']").validate({
// *** Validation Rules ***
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 60
},
repassword: {
required: true,
minlength: 8,
maxlength: 60,
equalTo: '#password'
},
agreeBox: {
required: true
}
},
// *** Validation error messages ***
messages: {
email: "Please enter a valid email address",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 8 characters long",
maxlength: "Your password can't be more than 60 characters"
},
repassword: {
required: "Please provide your password",
minlength: "Your password must be at least 8 characters long",
maxlength: "Your password can't be more than 60 characters",
equalTo: "Your password must equal your first password"
},
agreeBox: {
required: "Please read conditions and tick box"
}
},
submitHandler: function () {
ev.preventDefault();
var userEmail = $('input[id="emailId"]').val();
var userPass = $('input[id="passId"]').val();
$.ajax({
method: 'POST',
url: 'my database (this has been replaced)',
data: JSON.stringify({
name: userEmail,
password: userPass,
status: 'user',
}),
contentType: "Application/json",
dataType: "json",
success: function () {
swal("Lets Go Shopping!", {
buttons: {
confirm: "Go Shopping",
},
})
.then(() => {
window.location = 'index.html';
});
}
})
return false;
}
});
The issue that you have is with the AJAX call syntax or usage. You have used both success and then calls simultaneously. You need to have either success or then.
If you need success then it should be inside then like so.
$.ajax({
method: 'POST',
url: 'my database (this has been replaced)',
success: function( resp ) {
console.log('the success function', resp );
},
error: function( req, status, err ) {
console.log( 'Oops, something went wrong!!!', status, err );
}
});
or you can use .then() like so
$.ajax({
method: 'POST',
url: 'my database (this has been replaced)'
}).then( function( resp ) {
console.log('the success function', resp );
},
function( req, status, err ) {
console.log( 'Oops, something went wrong!!!', status, err );
});
Its like $.ajax({}).then(success, err)
Check out this post for further reading.

Pass variables to URL in ajax

I have the below ajax call in which I am trying to post the registration data directly to URL, but is there anyway I can store those variables and then pass it into the URL. Please help thank you in advance.
You can see the Script.js in this plunker
jquery:
$(function() {
/* Registration form for the website */
/* validation */
$("#register-form").validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
userName: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
},
messages: {
userName: "please enter a valid user name",
password: {
required: "please provide a password",
minlength: "password at least have 8 characters"
},
email: "please enter a valid email address",
cpassword: {
required: "please retype your password",
equalTo: "password doesn't match !"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm() {
var data = $("#register-form").serialize();
// var data={
// firstName: $('#firstName').val(),
// }
$.ajax({
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success: function(data) {
if (data === 0) {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
} else if (data == 1) {
$("#btn-submit").html('<img src="btn-ajax-loader.gif" /> Signing Up ...');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
});
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
become
url: 'http://localhost:8000?' + data,
type: 'GET',
//data: data,
Your AJAX URL is wrong, you do not need to type in the full address. The Serialize method should do that for you. All you need is localhost:8000? + data. And as #zer00ne said, never use a GET if your sending in a password, it will show up on the URL. As a rule of thumb, anything sent in a form should be a POST request, unless some rare cases which I am not aware of.
My suggestion:
$.ajax({
url: 'http://localhost:8000?',
type: 'POST',
data: data,
This way your sending in your information to the proper place and securely.

unable to send data via this.serialize

I am using following function to validate and send data to the php server:
$(document).ready(function () {
$(function() {
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
register_username: "required",
register_password: "required",
register_email: {
required: true,
email: true
},
register_confirm_password: {
required: true,
equalTo: '#register_password'
},
},
// Specify the validation error messages
messages: {
register_username: "Please enter your username",
register_password: "Please enter your password",
register_confirm_password: {
required: "Please provide a password",
equalTo:"Please enter password same as above."
},
register_email: "Please enter a valid email address",
},
submitHandler: function(form) {
var pdata = $(this).serialize();
alert(pdata);
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(this).serialize(),
dataType : 'json',
success: function(data) {
if (data.success){
console.log("Form is submitted.data is" + data.success);
$.each(data, function() {
$.each(this, function(k, v) {
console.log("key; " + k);
console.log("value; " + v);
});
});
}
else
{
console.log("The data returned is:" + data.success);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return false;
},
});
});
});
All the validation works, but the issue is with the line:
var pdata = $(this).serialize();
I am getting empty pdata:
alert(pdata);
I don't know why the data is not serialized here. Please help me to solve this.
Don't serialize $( this )
Try serializing the form instead.
$( "#register_form" ).serialize();
$(this) isn't what you think it is anymore. It's not #register_form, but instead the submitHandler function.
If you do console.log(pdata) you should see the function definition in your console.
The scope of the submitHandler function is not the form element, so this is not pointing to the element you require. It does however provide you with a parameter, which you've named form, that you can use instead, like this:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(form).serialize(),
// your code...

jquery validation - submitting form with enter key

I am new to javascript and jquery and I'm trying to submit a form which is validated using the jquery validation plugin using the enter key. This is my code but the form is not being submitted as the alert isn't showing when you press enter. I'm not sure what exactly is happening. I think the page is simply being reloaded when i press enter. There's certainly no validation
<script>
$(document).ready(function() {
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid_' + element.attr('id'));
}
});
var validator = $("#login_form").validate({
rules: {
user_email: {
required: true,
email: true
},
password: {
required: true
}
},
messages:{
user_email:{
required:"Email required",
email: "Must be a valid email"
},
password: {
required: "Password required"
}
},
submitHandler: function(form) {
alert('submitted');
$.ajax({
type: "POST",
url: "ajax/check_login.php",
data: $(form).serialize(),
timeout: 3000,
success: function(resp) {
if (resp == 'error') {
$('#login_error').html('Invalid login');
} else {
load_user_area();
}
},
error: function(e) {alert('failed' + e);}
});
return false;
}
});
$(document).keydown(function(e) {
if (e.keyCode == 13) { $('#login_form').submit(); }
});
});
</script>
Thanks in advance for any help!

Validating multiple forms with same class using jquery validate

I have about 10 forms on one page with the same class. Each form should be able to validate and send individually. I am using the jquery validate plugin. I can't get it to work and all the forms are submitting the first one. Besides that I can't seem to target the errormessage div within a form with $(this).find('.error').html(error);
Each form looks like this:
<form method="post" class="alertform" action="">
<input type="text" onclick="clearText(this)" value="" class="required email" name="email">
<input type="hidden" value="1000004011320719" name="productid" class="productid">
<input type="submit" class="button" name="button" value="Set alert">
<div class="error"> </div>
</form>
My JS:
$('.alertform').each( function(){
$(this).validate({
rules: {
emailadres: {
required: true,
email: true
}
},
messages: {
emailadres: {
required: "Message 1",
minlength: "Message 2",
email: "Message 3"
}
},
errorPlacement: function(error, element) {
$(this).find('.error').html(error);
},
success: function(label) {
label.addClass("valid").text("")
},
submitHandler: function() {
var emailadres = $(this).find("input.email").val();
var productid = $(this).find("input.productid").val();
var dataString = 'emailadres=' + emailadres + '&productid=' + productid;
$.ajax({
type: "POST",
url: "/setalert.php",
data: dataString,
success: function(msg) {
if (msg==1) {
$(this).find(".email").attr("value", "");
$(this).find('.error').html("Pricealert set.")
}
else {
$(this).find('.error').html("Oops.")
}
}
});
}
})
});
Any help is appreciated!
I had a look at your HTML n JS, can you try this?
$('.alertform').each( function(){
var form = $(this);
form.validate({
Basically change all your $(this) into form through out ur code
This is common mistake about $(this), sometime it lost its reference.
Hope helps
:)
The complete working JS:
$('.alertform').each( function(){
var form = $(this);
form.validate({
rules: {
emailadres: {
required: true,
email: true
}
},
messages: {
emailadres: {
required: "Required",
minlength: "Fill it in",
email: "Not valid"
}
},
errorPlacement: function(error, element) {
element.nextAll('div').html(error);
},
success: function(label) {
label.addClass("valid").text("")
},
submitHandler: function() {
var email = form.find("input.email").val();
var productid = form.find("input.productid").val();
var dataString = 'email=' + email + '&productid=' + productid;
$.ajax({
type: "POST",
url: "/myurl.php",
data: dataString,
success: function(msg) {
if (msg==1) {
form.find(".email").attr("value", "");
form.find('.error').html("Thanks")
}
else {
form.find('.error').html("Something went wrong")
}
}
});
}
})
});

Categories

Resources