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!
Related
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.
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.
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...
I have problem with jquery validate plugn and history API, when i click few times
i have error jquery.min.js?_=1420288991396:4 Uncaught TypeError: undefined is not a function, when I comment a fragment with validate, script works fine. How concat this script.
In file script.js i have:
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
},
submitHandler: function() {
var username=$("#usernameLogin").val();
var password=$("#passwordLogin").val();
var dataString = 'username='+username+'&password='+password+'&tag=login';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
if($("#rememberMe:checked").val()){
checkCookie(username);
}
window.location.href = "index.php";
}
else{
$("#error").html("<label class='error'>Wrong password or username!</label>");
console.log("Wrong password or username!");
}
}
});
}
return false;
}
});
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
},
messages: {
firstname: {
required: "Please enter your firstname",
minlength: "Your firstname must consist of at least 3 characters"
},
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function() {
var username=$("#username").val();
var password=$("#password").val();
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
var dataString = 'username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&tag=register';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
console.log(data);
$(".register_notification").html("<label class='error' style='background:#6DC066'>Register successfully!</label>");
}
else{
$(".register_notification").html("<label class='error'>Username already exists, please choose another one!</label>");
}
}
});
}
return false;
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if (firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
$("footer a").click(function(e){
//e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl,success: function(data){
$('#login_box').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function() {
if(!location.pathname.localeCompare('/login.php')){
$.ajax({url:location.pathname,success: function(data){
$('body').html(data);
}});
}
else{
$.ajax({url:location.pathname,success: function(data){
$('#login_box').html(data);
}});
}
});
From jQuery library:
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
it shows throw e.
I can't think of any reason why using the browser's "back" button would cause the JavaScript to fail. Everything should be cached and continue to work as before.
The error you're getting is similar to the error you'd get if you failed to include the plugin.
Here is how you're including the jQuery Validate plugin...
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
Notice how you're hotlinking to the plugin hosted on the developer's own domain. (likely for his demos and/or to download.) This error might be caused by a timing issue, the plugin not loading fast enough from this URL.
The developer has provided his plugin on two different free CDN services where "hotlinking welcome". So instead of leaching the plugin directly from his domain, try hotlinking to the CDN links provided here.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
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")
}
}
});
}
})
});