Validating multiple forms with same class using jquery validate - javascript

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")
}
}
});
}
})
});

Related

Submit login with Jquery

When I press the Login button I get a 500 Internal server error in the console. What's the right way to get POST using jQuery? Can you help me?
<button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
$(function() {
$("#Login").click(function() {
var username_val = $("#username").val();
var password_val = $("#password").val();
var info_creds = 'username=' + username_val + '&password=' + password_val;
if (username_val == '' || password_val == '') {
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Devi inserire username e password!</p>");
$("#alert_response_ko").fadeOut(8000);
} else {
$.ajax({
type: "POST",
url: "login.php",
data: info_creds,
cache: false,
success: function(response) {
if (response == 'wrong!') {
console.log('ko');
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Username e/o Password Errati!</p>");
$("#alert_response_ko").fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
}
}
});
}
return false;
})
});
The 500 Internal Server Error is a "server-side" error, meaning the problem is not with your PC or Internet connection but instead is a problem with the web site's server.
If you want to use Post, you have to send data as Object Change your
Ajax Function to...
$.ajax({
type: 'POST',
url: 'login.php',
data: {
username: username_val,
password: password_val,
},
cache: false,
success: function (response) {
if (response == 'wrong!') {
console.log('ko');
$('#alert_response_ko').show();
$('#alert_response_ko').html(
'<p>Username e/o Password Errati!</p>'
);
$('#alert_response_ko').fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function () {
window.location.href = './homepage.php';
}, 10);
}
},
});
Consider the following code.
$(function() {
function showAlert(msg) {
console.log(msg);
$("#alert_response_ko").html("<p>" + msg + "</p>").show().fadeOut(8000);
}
function login(page, user, pass) {
$.ajax({
url: page,
data: {
username: user,
password: pass
},
cache: false,
success: function(results) {
if (results == 'login_ok!') {
console.log('Login Successful');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
} else {
showAlert("Username e/o Password Errati!");
}
},
error: function(x, e, n) {
showAlert("Username e/o Password Errati! " + e + ", " + n);
}
});
}
$("#Login").closest("form").submit(function(e) {
e.preventDefault();
var username_val = $("#username").val();
var password_val = $("#password").val();
if (username_val == '' || password_val == '') {
showAlert("Devi inserire username e password!");
} else {
login("login.php", username_val, password_val);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="username" placeholder="User" /> <input type="password" id="password" placeholder="Password" /> <button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
</form>
<div id="alert_response_ko"></div>
This might help identify issues. As was suggested, the 500 status is a general Web Server failure. It means that the Web Server encountered an error and may be configured to suppress the error message itself.
Check your PHP Logs and Error handling settings. Better to reveal errors while testing and then hide them when in production.

Form validation not working before submit with ajax method

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.

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

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!

Categories

Resources