jQuery Validation Plugin - Form does not submit - javascript

I'm using the jQuery Validation Plugin, and I have a problem.
Both my jQuery and HTML is perfectly valid (according to JSLint and the WC3 Markup Validation Service), but when I hit the submit button, nothing happens.
My code even clearly states that, upon submitting, an alert should pop up, but even that doesn't work. The form is however validated correctly, and in the and, all fields are green (meaning they passed validation) but it doesn't actually submit (nothing happens).
Also, in my DevTools, the console does not report any errors.
Possibly/probably relevant; the email-textfield and the username-textfield are both being checked by a remote PHP script. This script works, strange enough, only after the second time. So when I first leave (blur) the email-textfield, nothing happens, it's isn't marked correct nor false.
Only when I (re-enter and) leave the textfield for the second time, it is validated, or when I hit the submit button. (This shows the submit button is actually connected, it just simply does not submit)
I really hope someone will solve my problem. I'm not trying to just let someone else do the work. I validated, checked, debugged, but nothing solved my problem.
My HTML (it's in a modal using Bootstrap):
<div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="signupform" method="post" action="/" role="form">
<div class="modal-body" style="padding-bottom: 5px;">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<p class="lead">For creating an account,</p>
<p class="lead text-right">you'll have to give us some information.</p>
<div id="emailgroup" class="form-group">
<label for="signupemail"> Your Emailaddress</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-envelope"></span> </span>
<input type="email" name="signupemail" spellcheck="false" autocomplete="on" required class="form-control" id="signupemail" placeholder="Email">
</div>
<label class="control-label error-label" for="signupemail"></label>
</div>
</div>
<div id="fnamegroup" class="form-group">
<label for="inputfname"> Your Full Name</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-user"></span> </span>
<input type="text" name="fname" required class="form-control" id="inputfname" placeholder="Barack Obama">
</div>
<label class="control-label error-label" for="inputfname"></label>
</div>
</div>
<div id="unamegroup" class="form-group">
<label for="inputuname"> Your Username</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> # </span>
<input type="text" name="uname" required class="form-control" id="inputuname" placeholder="PresidentofAmerica">
</div>
<label class="control-label error-label" for="inputuname"></label>
</div>
</div>
<div id="thepasswordgroup" class="form-group">
<label for="thepassword"> Your Password</label>
<div class="col-lg-10">
<div class="input-group">
<span class="input-group-addon"> <span class="glyphicon glyphicon-lock"></span> </span>
<input type="password" name="thepassword" required class="form-control" id="thepassword" placeholder="123456789" autocomplete="off">
</div>
<label class="control-label error-label" for="thepassword"></label>
</div>
</div><br />
<div id="gendergroup">
<label>Your Gender</label>
<div class="radio">
<label class="checkbox-inline"><input type="radio" name="gendergroup" id="gendergroupmale" value="male" checked>I'm a Male</label>
</div>
<div class="radio">
<label class="checkbox-inline"><input type="radio" name="gendergroup" id="gendergroupfemale" value="female">I'm a Female</label>
</div>
</div>
<br />
<div class="form-group">
<label for="taccheckbox"> Terms and Conditions</label>
<div class="col-lg-10">
<div class="input-group"><span class="input-group-addon">
<input id="taccheckbox" name="taccheckbox" type="checkbox" required>
</span>
<input style="cursor:default !important;" type="text" id="something" value="I accept the Terms and Conditions" readonly class="form-control">
</div>
<label class="control-label error-label" for="taccheckbox"></label>
<!-- /input-group -->
</div>
<!-- /.col-lg-6 -->
</div>
</div>
<div class="modal-footer">
<p>
Have already got an account? <strong>Login here!</strong></p>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="signupsubmitbtn" class="btn btn-primary" value="Sign Up">
</div>
</form>
</div>
</div>
</div>
My Javascript/jQuery:
$('#signupform').validate({
rules: {
signupemail: {
required: true,
email: true,
remote: {
url: "/functions/verifysignup.php",
type: "post"
}
},
fname: {
required: true,
minlength: 8,
maxlength: 30
},
uname: {
required: true,
minlength: 6,
maxlength: 20,
remote: {
url: "/functions/verifysignup.php",
type: "post"
}
},
thepassword: {
required: true,
minlength: 5,
maxlength: 20
},
taccheckbox: "required"
},
messages: {
email: {
remote: "This emailaddress is already in use"
},
taccheckbox: {
required: "You have to accept the Terms and Conditions"
},
fname: {
minlength: "At least 8 characters required",
maxlength: "Max. 30 characters"
},
uname: {
minlength: "At least 6 characters required",
maxlength: "Max. 20 characters",
remote: "This username is already in use"
}
},
submitHandler: function (form) {
alert('called');
$('#signupsubmitbtn').prop("disabled", false);
//^[a-zA-Z0-9_-]{6,15}$ username
form.submit();
},
errorPlacement: function (error, element) {
if (element.attr('id') == "taccheckbox") {
error.appendTo(element.parent().parent().next());
} else {
error.appendTo(element.parent().next());
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
$('#signupsubmitbtn').prop("disabled", true);
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error').find('label.control-label label').text('');
if ($('.has-error').length === 0) {
$('#signupsubmitbtn').prop("disabled", false);
}
},
success: function (element) {
element.closest('.form-group').removeClass('has-error').addClass('has-success');
if ($('.has-error').length === 0) {
$('#signupsubmitbtn').prop("disabled", false);
}
//element.parent().next().text('');
}
});
My remote PHP script:
<?php
define ('INCLUDE_CHECK',true);
require('connect.php');
if(isset($_REQUEST['signupemail'])){
$email = mysqli_real_escape_string($link, $_REQUEST['signupemail']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE email=\"".$email."\""));
if($thearray[0] > 0){
echo '"This emailaddress is already in use"';
} else {
echo "True";
}
} else if(isset($_REQUEST['uname'])){
$uname = mysqli_real_escape_string($link, $_REQUEST['uname']);
$thearray = mysqli_fetch_array(mysqli_query($link, "SELECT COUNT(*) FROM `users` WHERE uname=\"".$uname."\""));
$forbiddennames = array(1 => 'super-user','superuser', 'root', 'admin', 'administrator', 'system', 'website', 'site', 'owner', 'manager', 'founder','moderator');
if(in_array(strtolower($_REQUEST['uname']), $forbiddennames)) {
echo '"'.$_REQUEST['uname'].' is a forbidden username"';
} else if($thearray[0] > 0){
echo '"This username is already in use, please choose another"';
} else {
echo "True";
}
}
?>

Everything looks very close to correct to me. One issue is that you have your php script echoing True back, but it has to be true (lower case). That actually matters.
Otherwise, IMO your script looks fine.
The stuff you're saying about it not calling your submitHandler, or only triggering the remote bits doesn't really seem to be the case to me. I copied your code and simply added a bit of debugging (i.e. to console.log when remote gets triggered or when submitHandler gets called) and both got called at the appropriate times.
For instance, if you type a valid email and then click to the next field, it immediately validates the email address.
So whatever issues you're having, are not related to the code you've shown (except for that one error with true vs True).
Here's a working example of your code, for reference: http://jsfiddle.net/ryleyb/tWH9M/1/
In order to test it with remote working teh way you have it setup, you have to find this bit:
signupemail: {
required: true,
email: true,
remote: {
url: '/echo/json/',
data: {
json: function () {
return 'true';
}
},
complete: function (data) {
$('#log').append('remote signupemail triggered<br>');
},
type: 'post'
},
},
And change that return 'true'; to return 'True';

Related

Unable to keep preventDefault when using a submitHandler, goes straight to AJAX PHP file

I'm unable to keep my AJAX call inside the same page. It keeps posting my form without any of the tried preventDefault() tries.
Here's my full code for a form ID "#leadform" and a button ID "#submitButton".
$(document).ready(function() {
$("#submitButton").on('click', function(e) {
e.preventDefault();
$('#leadform').submit();
});
$("#leadform").validate({
rules: {
Mobile: {
required: true
},
email: {
required: true
}
},
messages: {
Mobile: {
required: "Please enter a valid phone number"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$("#response").addClass("alert alert-info").text("Do not close this window, it may take a minute to complete!");
var formData = $('#leadform').serialize();
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
dataType: 'text', // json
beforeSend: function(data) {
//console.log(data);
},
success: function(data) {
$("#response").removeClass("alert-info").delay(200).addClass("alert-success").text("Thank you for your request! You can now close this window");
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
}
});
return false;
}
});
});
I have tried a lot of options, read about all the SO posts and none helped.
Alternatives I tried are:
Without $('#leadform').submit(); called seperately, but from within the same function.
e.preventDefault from within the submithandler (added e to the function of course).
Tried with and without that return false line.
Whatever I tried (tried for hours literally), it goes straight to the php file. When I remove the validate function and include the ajax normally via the submit button click function, it works fine and as expected (it just won't validate my last step in the form wizzard so i need to make a validation for that last step.
I hope anybody can help me out.
Thanks.
Added HTML Section (shortened)
<form action="submit.php" name="leadform" id="leadform" method="POST" accept-charset="utf-8" class="js-wizard-validation2-form">
<div id="_Mobile" class="form-group">
<label class="control-label" for="Mobile">Mobile Number</label>
<input type="text" name="Mobile" id="Mobile" minlength="10" maxlength="16" placeholder="Phone number here" class="form-control required input_text" required="">
</div>
<div id="_Email" class="form-group">
<label class="control-label" for="Email">Email Address</label>
<input type="email" name="Email" id="Email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" placeholder="Email here" autocorrect="off" autocapitalize="off" class="form-control input_text" required="">
</div>
<div class="block-content block-content-sm block-content-full bg-body-light rounded-bottom" style="margin-top:20px;">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-lg btn-alt-secondary" data-wizard="prev">
<i class="fa fa-angle-left mr-1"></i> Previous
</button>
</div>
<div class="col-6 text-right">
<button type="button" class="btn btn-lg btn-info" data-wizard="next">
Next<i class="fa fa-angle-right ml-1"></i>
</button>
<button type="submit" id="submitButton" class="btn btn-lg btn-success d-none" data-wizard="finish">
<i class="fa fa-check mr-1"></i> Submit </button>
</div>
</div>
</div>
</form>
According to the docs, you can actually trigger the validator without submitting the form.
var validator = $( "#leadform" ).validate();//your entire validation script goes here, its left out for brevity
$("#submitButton").on('click', function(e) {
e.preventDefault();
validator.form();
});

$(this).serialize() not working in jQuery validate submitHandler

I have a situation where i have the same form multiple times on a page in my application which allows users to edit or remove data however when using the below javascript to listen for the form submission the page just refreshes.
I was going to use $('.service_form').serialize() to submit the forms however when doing so it serializes values from every form on the page and completes the ajax request however if i use $(this).serialize() the page just refreshes.
HTML Form
<div id="service_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form class="service_form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class='form-group has-feedback has-feedback-left'>
<label for="service_idno">IDNO:</label>
<input type="text" class="form-control required" id="service_idno" name="service_idno">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_code">Service Code:</label>
<input type="text" class="form-control required" id="service_code" name="service_code">
</div>
<div class='form-group has-feedback has-feedback-left'>
<label for="service_cost">Service Cost:</label>
<input type="number" class="form-control required" id="service_cost" name="service_cost">
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Commit" class="btn btn-success" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
Javascript
$('.service_form').each(function(){
$(this).validate({
errorClass: 'validation-error-label',
highlight: function(element, errorClass) {$(element).removeClass(errorClass);},
errorPlacement: function(error, element){if (element.parents('div').hasClass('has-feedback')) {error.appendTo(element.parent() );}},
rules:{vali: "required"},
messages: {
service_idno: {required: "* Service IDNO Is Required."},
service_code: {required: "* Service Code Is Required."},
service_name: {required: "* Service Name Is Required."},
service_account: {required: "* Account Is Required."},
service_cost: {required: "* Cost Is Required."},
service_retail: {required: "* Retail Is Required."},
},
submitHandler: function(form) {
$.ajax({
url: "rest/servicedelete.php",
type: "POST",
data: $(this).serialize(),
timeout:9000,
beforeSend:function() {
$('.modal').modal('hide');
},
success: function (data) {
},
error:function() {
$('#notification').html('Remote Service Currently Unavailable');
},
});
}
});
});
I am wanting to be able to submit any form on the page at any time and only submit that data.
The scope of submitHandler() is not the form element, hence this is not what you expect it to be. Use the provided form parameter instead:
data: $(form).serialize(),
first you need to store current form in a temp variable like
$('.service_form').each(function(){
var form = $(this);
and then you do the serialize like
data: $(form).serialize(),
that will fix your issue.

MS Edge: form submitted even if return false

I got a strange problem when creating a login form for a website I create for work. I know it has been posed a million times but my case only breaks in Edge.
Principle is: I have a form with username and password. When submitting the form user and pass is validated and logged in in ajax (and returns error if so). If valid it redirects to the main user. (simple, no?)
Problem is that the page is refreshed anyway even if the form have return: false, but only in Microsoft Edge. It works on Chrome, IE (even in document mode 10) and Firefox with no problems.
Code in action:
<!-- jQuery + validate plugins are already loaded -->
<form id="loginform" method="post" class="">
<div class="navbar-login panel">
<div class="panel-heading">
<h4 class="panel-title">Connexion au cours</h4>
</div>
<div class="panel-body">
<div id="login-warning"></div>
<div class="form-group col-md-12">
<input class="form-control" style="width: 100%;" placeholder="Adresse email" name="LOGIN_EMAIL" type="email">
</div>
<div class="form-group col-md-12">
<input class="form-control" style="width: 100%;" placeholder="Mot de passe" name="LOGIN_PASSWORD" type="password">
</div>
</div>
<div class="panel-heading text-right" style="display: table;width: 100%;">
<button type="submit" style="float: right;display: inline-block;" class="btn btn-info">Connexion</button>
</div>
</div>
</form>
JS:
$("#loginform").validate({
debug: false,
rules: {
LOGIN_EMAIL: {
required: true,
email: true
},
LOGIN_PASSWORD: {
minlength: 6
}
}
});
$("#loginform").submit(function(e){
var f = $(this);
if(f.valid()){
$.ajax({
url: "req/ajx_login.php",
type:"POST",
cache: false,
async: false,
data: f.serialize(),
success: function(data, status, xhr){
// data is "success" if successed, anything else if failed
if(data == "success"){
location = "/cours";
}else{
$("#login-warning").html(data);
}
}
});
}
return false;
});
Can someone help? Thanks for future answers.

jquery validation with php form

I am trying to use jquery validation for a php form to change your password but I keep getting the error "Your password must be the same as above" when the password is correct. I can't seem to find out where I have went wrong at all... Here's the JS code
var changepassword = function() {
return {
init: function() {
/*
* Jquery Validation, https://github.com/jzaefferer/jquery-validation
*/
$('#changepassword').validate({
errorClass: 'help-block animation-slideUp',
errorElement: 'div',
errorPlacement: function(error, e) {
e.parents('.form-group > div').append(error);
},
highlight: function(e) {
$(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
$(e).closest('.help-block').remove();
},
success: function(e) {
if (e.closest('.form-group').find('.help-block').length === 2) {
e.closest('.help-block').remove();
} else {
e.closest('.form-group').removeClass('has-success has-error');
e.closest('.help-block').remove();
}
},
rules: {
'newpassword': {
required: true,
minlength: 6
},
'newpassword-verify': {
equalTo: '#newpassword',
required: true
}
},
messages: {
'newpassword': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long'
},
'newpassword-verify': {
required: 'Please provide a password',
minlength: 'Your password must be at least 6 characters long',
equalTo: 'Please enter the same password as above'
}
}
});
}
};
}();
This is the PHP/HTML for the form
<form method="POST" class="form-horizontal form-bordered" id="changepassword">
<div class="form-group">
<label class="col-md-3 control-label" for="newpassword">New Password</label>
<div class="col-md-6">
<input type="password" id="newpassword" name="newpassword" class="form-control" placeholder="New Password" required>
</div>
</div>
<!-- This is where I keep getting the error -->
<div class="form-group">
<label class="col-md-3 control-label">Repeat Password</label>
<div class="col-md-6">
<input type="password" id="newpassword-verify" name="newpassword-verify" class="form-control" placeholder="Repeat Password" required>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="oldpassword">Current Password</label>
<div class="col-md-6">
<input type="password" id="oldpassword" name="oldpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="form-group form-actions">
<button type="submit" name="update" class="btn btn-block btn-primary">Update</button>
</div>
</form>
Sorry, I was able to fix it by making a new file called settings1.php then removing the old one and renaming the new one with the old name.

add class to footer after click button from submit

Hello i'm new in php and javascript developer and i have a question.
i have an html file with a form for registration and a footer section
In the registration form when i add sucessfully a user i hide the input text and show a message, but the footer section go up.
For fix this visual problem i want add the "footer-fixed-bottom" to fotter section but only when hide the input text in this way i block the footer at the end of page.
i have an html and a java script in external file... my problem is access to footer section from javascript.
html code
<section class="page-login section-4">
<div class="container">
<div class="row">
<div class="col-sm-10 col-sm-offset-1 col-md-6 col-md-offset-3">
<div class="well well-6 mb0">
<h2 class="section-title-2 st-2 mb20">Registrazione</h2>
<p>Possiedi gi&agrave un account ? Login</p>
<form id="RegistrationForm" class="register-form form form-2" method="post" action="php/registrati.php">
<label>
Nome Utente
<input name="name " id="name" type="text" required class="form-control" placeholder="Nome">
</label>
<label>
Email <span class="required">*</span>
<input name="email " id="email" type="email" required class="form-control" placeholder="Email">
</label>
<label>
Password <span class="required">*</span>
<input name="password " id="password" type="password" required class="form-control" placeholder="Password">
</label>
<label>
Confirm Password <span class="required">*</span>
<input name="confirmpassword" id="confirmpassword" type="password" required class="form-control" placeholder="Confirm Password">
</label>
<label class="hideFormcontrol">
<input type="checkbox" name="terms" id="terms" value="ok" required class="hideFormcontrol">
Acconsento a DBSoftware Termini e condizioni e Privacy
</label>
<div class="alert alert-success hidden br0" id="contact-success">
<span class="glyphicon glyphicon-ok "></span>
<strong>Success!</strong> Grazie per esserti registrato.
</div>
<div class="alert alert-danger hidden br0" id="contact-error">
<span class="glyphicon glyphicon-remove "></span>
<strong>Error!</strong> Le password inserite non corrispodono.
</div>
<div class="alert alert-danger hidden br0" id="contact-present">
<span class="glyphicon glyphicon-remove "></span>
<strong>Error!</strong> Email gi&agrave presente nel database.
</div>
<div>
<input type="submit" class="hideFormcontrol btn voyo-btn-2 rounded mt5" value="Registrati">
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer class="footer-wrapper no-border" >
<div class="sub-footer">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="pull-left">
<p>© Copyright 2015 DBSoftware</p>
</div>
<div class="pull-right">
<ul class="social-icon dark-2 rounded">
<li><i class="fa fa-facebook"></i></li>
<li><i class="fa fa-twitter"></i></li>
<li><i class="fa fa-google-plus"></i></li>
<li><i class="fa fa-tumblr"></i></li>
<li><i class="fa fa-rss"></i></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- END Sub footer -->
</footer>
<!-- END Footer -->
jscript with validate code
if ($('.register-form').length) {
var form = {
init: false,
initialize: function () {
// if form is already initialized, skip
if (this.init) {
return;
}
this.init = true;
var $form = $(".register-form");
$form.validate({
submitHandler: function (form) {
// Loading Button
var btn = $(this.submitButton);
btn.button("loading");
// Ajax Submit
$.ajax({
type: "POST",
url: $form.attr("action"),
data: {
"name": $form.find("#name").val(),
"email": $form.find("#email").val(),
"password": $form.find("#password").val(),
"confirmpassword": $form.find("#confirmpassword").val(),
"terms": $form.find("#terms").val()
},
dataType: "json",
success: function (data) {
var $success = $form.find("#contact-success"),
$error = $form.find("#contact-error"),
$present = $form.find("#contact-present");
switch (data.response) {
case "success":
$success.removeClass("hidden");
$error.addClass("hidden");
$present.addClass("hidden");
//Reset Form
$form.find(".form-control")
.val("")
.blur()
.parent()
.removeClass("has-success")
.removeClass("has-error")
.addClass("hidden")
.find("label.error")
.remove();
$form.find(".hideFormcontrol")
.addClass("hidden")
break;
case "error":
$error.removeClass("hidden");
$success.addClass("hidden");
$present.addClass("hidden");
break;
case "present":
$error.addClass("hidden");
$success.addClass("hidden");
$present.removeClass("hidden");
break;
}
},
complete: function () {
btn.button("reset");
}
});
},
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
password: {
required: true
},
confirmpassword: {
required: true,
equalTo: "#password"
},
terms: {
required: true
}
},
messages: {
name: {
required: "<span class='form-message-error'>Please enter your name!</span>"
},
email: {
required: "<span class='form-message-error'>Please enter your email address!</span>",
email: "<span class='form-message-error'>Please enter a valid email address!</span>"
},
password: {
required: "<span class='form-message-error'>Please enter a password!</span>"
},
confirmpassword: {
equalTo: "<span class='form-message-error'>Prego, inserire la stessa password!</span>"
},
terms: {
required: "<span class='form-message-error'>Prego, selezionare le condizioni della privacy!</span>"
}
},
highlight: function (element) {
$(element)
.parent()
.removeClass("has-success")
.addClass("has-error");
},
success: function (element) {
$(element)
.parent()
.removeClass("has-error")
.addClass("has-success")
.find("label.error")
.remove();
}
});
} // END initialize
}; // END form object
form.initialize();
}
i want add in the jscript a part where i can addclass in the footer section class. In the jscript i can access to all element in the form section but i can't access the element out of form section, how can reference to footer section in the section code?
case "success":
$success.removeClass("hidden");
$error.addClass("hidden");
$present.addClass("hidden");
//Reset Form
$form.find(".form-control")
.val("")
.blur()
.parent()
.removeClass("has-success")
.removeClass("has-error")
.addClass("hidden")
.find("label.error")
.remove();
$form.find(".hideFormcontrol")
.addClass("hidden")
break;
thanks a lot for help.
You can use element/type selector to select the <footer>, and use addClass() to add a class to the element.
Using type selector:
$('footer').addClass('footer-fixed-bottom');
Using class selector:
$('.footer-wrapper').addClass('footer-fixed-bottom');

Categories

Resources