When I submit the form without filling in any information it quickly displays the error message then fades. I only want the form to fade if there's no error messages and the validation is successful. I think I may need to use an if statement for success or something to do with a submit handler?
So far I have this - https://jsfiddle.net/wnmLmcm8/
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
}
});
});
$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
}
});
});
Here is a working version of your jsFiddle: https://jsfiddle.net/ywhpdLen/3/
This snippet works, based off of your jsFiddle, but your jsFiddle does not work. I had to pull the code into my own dev environment, locally.
The popup stays until you click in the text field.
Adding "required" to the input elements & using the default ".validate()" extension does the job. If you're looking to customize it, I'd highly recommend looking at https://jqueryvalidation.org/documentation/
<div id="emailform">
<form method="post" action="form.php">
<hr>
<label for="name">Name</label>
<br>
<input type="text" name="name" id="name" class="NewsLetter1" required/>
<br>
<label for="email">Email</label>
<br>
<input type="text" name="email" id="email" class="NewsLetter2" required/>
<input type="submit" value="Submit">
<hr>
</form>
</div>
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
},
failure: function (ex) {
}
});
});
$("form").validate();
});
</script>
Per comments, below: It looks like your ajax call is still happening and form.submit() is firing off. You may want to remove your form.submit() call and include it in the validate call, like so.
$("form").validate({
submitHandler:function(form){
$.ajax({....})
}
});
Do it with submit handler like...
$(document).ready(function ()
{
$("form#sub_form").validate({
rules: {
UserName: "required",
Useremail: {
required: true,
email: true
},
Userpwd:{
required: true,
minlength:8
},
Con_Userpwd:{
required:true,
equalTo:"#reg-pass"
},
contact:{
required:true,
minlength:10
}
},
messages: {
UserName: "Please specify your name",
Useremail: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name#domain.com"
},
Userpwd:{
required: "Enter Your Password",
minlength:"Please Enter minimum 8 digit password"
},
Con_Userpwd: {
required:"Please re-enter your password",
equalTo:"Password not matched"
},
contact:{
required:"Phone Number Required",
minlength:"Minimum 10 Digits Required"
}
},
submitHandler: function(form) {
var msg = $("form#sub_form").serialize();
$.ajax({
type: "POST",
url: "register_checkout.php",
data: msg,
success: function (html) {
$(".popup").delay(5000).fadeOut(1500);
setTimeout(function(){window.location='one-page-checkout.php'},3000);
//return false;
}
else
{
$("#reg_message").slideUp();
$("#reg_message").slideDown().html(html);
}
}
}
);
Try putting your ajax into submitHandler of validation plugin
$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
},
submitHandler:function(form){
$.ajax({....})
}
});
When running into problems use debug:true
for instant solution use "required" https://jsfiddle.net/et7qcrye/
<input type="text" name="name" id="name" class="NewsLetter1" required/>
Related
I have a form , after validate I take data and update the hidden form that I popup or just need to be hidden and need to be posted to the action.
from hidden I do manual submit from code
the bug is that always post by submit lead to refresh the page instead. redirecting
my js code:(could be typo) . - form validate
form.validate({
ignoreTitle: true,
onfocusout: function (element) {
if (!this.checkable(element)) {
this.element(element);
}
},
onkeyup: false,
rules: {
firstName: {required: true, minlength: 2, maxlength: 45},
lastName: {required: function () {
return checkField("lastName")
}, minlength: 2, maxlength: 45},
},
messages: {
firstName: {required: FieldRequiredStr, minlength: invalidFirstName, maxlength: invalidFirstName},
lastName: {required: FieldRequiredStr, minlength: invalidLastName, maxlength: invalidLastName},
},
onsubmit: true,
submitHandler: function (frm) {
if(!form.valid())return;
$("#send",form).attr('disabled', 'disabled');
$("#send",form).addClass('sent');
form.ajaxSubmit(
{
url: "api.php",
dataType: 'xml',
success: function (response) {
var xml;
if (typeof response == 'string') {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(response);
}
var url = "https://url/login"
console.log(url);
$('#frm2').attr('action', url );
$('#email').val($("#email",frm).val());
$('#password').val($("#password",frm).val());
// $.fancybox({href: '#make-deposit'});
//$("#frm2").submit();
//
setTimeout(function () {
$("#frm2").submit();
}, 2000);
}
}
});
},
errorPlacement: function (error, element) {
//this is working good
// A bit ugly.
}
my hidden form (even if it is not hidden click on submit will casue refresh)
<div style="display:none;">
<form id="frm2" method="post" action="https://url/login" target="">
<input type="hidden" id="email" name="email" value="" />
<input type="hidden" id="password" name="password" value="" />
<input class="dbtn" type="submit" name="btn" id="btn" value="btn" />
</form>
</div>
It's working without slash at the end in the url on action
But the post data is not send in that case
It happens because the form IS submitted. You need to return false in your submithandler, like this:
submitHandler: function (frm) {
//Your code here
return false;
}
in submit handler function, use
e.preventDefault();
e.stopPropogation();
where e being the event passed.
I have one form and fields are Fullname, Password and Mobile no and each field has the single button. All the fields are displaying single in the page. If the user clicked on the button then next field will display but I have to set the validation on it using AJAX. I have to display the error single on each field. Would you help me in this?
I tried below code but I am getting false output in the alert.
My controller
public function submit_from(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fullname', 'fullname', 'required|min_length[5]|max_length[20]|trim|xss_clean');
$this->form_validation->set_rules('password', 'password', 'required|min_length[5]|max_length[20]|trim|xss_clean');
$this->form_validation->set_rules('mobile', 'mobile', 'required|min_length[5]|max_length[20]|trim|xss_clean');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors();
}
else
{
echo "true";
}
}
View
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#password_form, #mobile_form{
display: none;
}
</style>
</head>
<body>
<form class="active_form" name="form_1" method="post">
<div id="name_form">
<!--Name form********************************************************-->
<label>Full name</label>
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<?php echo form_error('fullname'); ?>
<button type="button" id="continue_to_password">Continue to Password</button>
</div>
<!--password form********************************************************-->
<div id="password_form">
<label>Password</label>
<input type="password" name="password" id="password" placeholder="password name">
<?php echo form_error('password'); ?>
<button type="button" id="continue_to_mobile">Continue to mobile no</button>
</div>
<!--mobile form********************************************************-->
<div id="mobile_form">
<label>Mobile number</label>
<input type="text" name="mobile" id="mobile" placeholder="mobile no">
<?php echo form_error('mobile'); ?>
<button type="submit">Submit</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('form[name="form_1"]').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?php echo base_url("index.php/testcontroller/submit_from"); ?>',
data: $('form[name="form_1"]').serialize(),
success: function (data) {
alert(data);
}
});
});
});
/*When clicked on button*/
$('body').on('click', '#continue_to_password', function(e) {
$('#name_form').hide();
$('#password_form').show();
});
$('#continue_to_mobile').on('click', function() {
$('#password_form').hide();
$('#mobile_form').show();
});
</script>
</body>
</html>
I tried client side validation using Jquery but this is also working at the end when I clicked on submit button.
Jquery
$(document).ready(function() {
$(".active_form").validate({
rules: {
fullname: {
required: true,
minlength:3,
maxlength:50
},
password: {
required: true,
minlength:3,
maxlength:50
},
mobile: {
required: true,
minlength:3,
maxlength:50
}
},
})
$('#continue_to_password').click(function() {
$(".active_form").valid();
});
});
You may see the result of your validation:
if ($this->form_validation->run() == FALSE) {
echo validation_errors();
}
Please see this post it may help you...
Do form validation with jquery ajax in codeigniter
For validation using jQuery with ajax submit you can try this script.
jQuery(function($){
$(".active_form").validate({
rules: {
fullname: {
required: true,
minlength:3,
maxlength:50
},
password: {
required: true,
minlength:3,
maxlength:50
},
mobile: {
required: true,
minlength:3,
maxlength:50
}
},
submitHandler: function (form) {
var request;
// bind to the submit event of our form
// let's select and cache all the fields
var $inputs = $(".active_form").find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $(".active_form").serialize();
//alert(serializedData);
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
request = $.ajax({
url: "http://ajax/function/url/here",
type: "POST",
data: serializedData,
});
// callback handler that will be called on success
request.done(function(data) {
// log a message to the console
alert("success awesome");
});
request.fail(function (jqXHR, textStatus, errorThrown) {
// log the error to the console
});
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
});
});
Finally, I found My solution. I don't know it's the correct way to do but it's solved my issue.
$(document).ready(function() {
$("form[name='form_1']").validate({
rules: {
fullname: {
required: true,
minlength:3,
maxlength:50
},
password: {
required: true,
minlength:3,
maxlength:50
},
mobile: {
required: true,
minlength:3,
maxlength:50
}
},
})
$('body').on('click', '#continue_to_password', function(e) {
if($("form[name='form_1']").valid())
{
$('#name_form').hide();
$('#password_form').show();
}
});
$('#continue_to_mobile').on('click', function() {
if($("form[name='form_1']").valid()){
$('#password_form').hide();
$('#mobile_form').show();
}
});
});
I have a basic login form and I've specified the form validations and API call in my javascript file. The problem that I have is, when I click the login button and the form has errors, the invalid fields will be highlighted but the API call is still made, even though the form is invalid.
Here's a simplified example:
<form class="ui form">
<div class="field">
<input name="username" type="text" placeholder="Username" autofocus>
</div>
<div class="field">
<input name="password" type="password" placeholder="Password">
</div>
<button type="submit" class="ui submit button">Login</button>
<div class="ui error message"></div>
</form>
$(function() {
$('form').form({
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Please enter your username'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'empty',
prompt: 'Please enter your password'
}]
}
}, {
onFailure: function() {
// prevent form submission (doesn't work)
return false;
}
});
// *** this API call should not be made when the form is invalid ***
$('form .submit.button').api({
action: 'login',
method: 'post',
serializeForm: true,
dataType: 'text',
onSuccess: function() {
// todo
},
onError: function() {
// todo
}
});
});
I also have a punkr here which demonstrates the issue I'm having.
Did I miss something? Are the .api() and .form() calls correct?
Ok I figured it out. All I need to do is change
$('form .submit.button').api(...
to
$('form').api(...
I didn't realise that I could call .api() directly on the <form> element. Now the api call isn't made when the form is invalid because the form isn't submitted (previously I had the api call on the submit button which isn't cancelled when the form is invalid).
Use onSuccess event instead of api method.
$('form').form({
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Please enter your username'
}]
},
password: {
identifier: 'password',
rules: [{
type: 'empty',
prompt: 'Please enter your password'
}]
}
}, {
onFailure: function() {
// prevent form submission (doesn't work)
return false;
},
onSuccess:function(event,fields){
// prevent form submission
// api / ajax call
return false;
}
});
Hello I've a html form which validate by php with Ajax. After successfully insert all data to db it's show a Successfull message on html form. But Now I want hide the hitml form when it's showing me Successfull message. Following is my Ajax code..
<script>
$(document).ready(function() {
// validate signup form on keyup and submit
$("#form1").validate({
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
//async: false,
data: $(form).serialize(),
beforeSend : function (){
$('input[type=submit]').attr('disabled', false);
},
success: function(response) {
$('#info1').html(response);
$(form).find('#form1').hide();
//return false;
setTimeout(function() {
$('input[type=submit]').attr('disabled', false);
location.reload();
}, 5000 );
}
});
},
rules: {
title: "required",
firstname: "required",
lastname: "required",
company: "required",
position: "required",
password: {
required: true,
minlength: 8
},
email: {
required: true,
email: true,
remote: {
url: "checkEmail.php",
type: "post"
}
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
terms: "required"
},
messages: {
title : "Required",
firstname: "Required",
lastname: "Required",
position: "Required",
company: "Required",
password: {
required: "Required",
minlength: "password must be at least 8 characters long"
},
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
},
terms: "Required"
}
});
});
</script>
I'm using this code to hide the html form but it's don't hind.
$(form).find('#form1').hide();
Html form
<div id="info1">
</div>
<form id="form1" method="post" action="<?php echo htmlspecialchars("regProcess.php") ?>">
<table width="100%" border="0" cellspacing="10" cellpadding="0">
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value="<?php if(isset($_POST['fname'])) echo $_POST['fname']; ?>" class="tr" placeholder="First Name"/></td>
</tr>
<!--more field-->
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit" value="Register" class="submit_button"/></td>
</tr>
</table>
You don't need .find(), change to:
$(form).hide();
The variable form is your form object, so you can simply add a jQuery wrapper and call .hide(). By using .find() you are asking jQuery to look for another form within your form, which isn't right.
Try this..
$("#form1").hide();
There is no need of find for hiding..
You can also use CSS style property..
document.getElementById('form1').style.display = 'none';
try,
$("#form1").css("display","none");
$.ajax({
url: form.action,
type: form.method,
//async: false,
data: $(form).serialize(),
beforeSend : function (){
$('input[type=submit]').attr('disabled', false);
},
success: function(response) {
$('#info1').html(response);
$('#form1').hide();
//return false;
setTimeout(function() {
$('input[type=submit]').attr('disabled', false);
location.reload();
}, 5000 );
}
});
Simply use $(from).hide(); instead of $(form).find('#form1').hide(); once you get response from ajax call, your existing form will hide.
Just do $('#form1').hide(); directly. That should work. Just be wary that it will be visible again when the page reloads in 5000 milliseconds. If that doesn't work, then there must be something else going on because what you have up there should work.
The form object and the #form1 that u try to find, are the same element, you must use:
$('#form1').hide();
or try:
$(form).hide();
This is using jQuery 1.6.1 and Validate 1.8.1.
I have been banging my head against a wall because of this problem, and now I'm trying the other approach to try and solve this problem. I need to query the database for existing usernames so that someone signing up doesn't register the same one again.
HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
This time, I'm trying to use the remote function for the validate script:
$("#signup").validate( {
var username = $("#username").val();
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
},
},
submitHandler: function(form) {
form.submit();
}
});
The code in question that doesn't work is var username = = $("#uname").val();. Firebug gives the error missing : after property id.
I'm including the mentioned variable above inside validate() because I only want the value of the input after I've typed something into it, not upon loading of the page.
The other problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
What am I doing wrong?
As you can read How can I force jQuery Validate to check for duplicate username in database?
The solution is to use the remote property:
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
var username = $("#uname").val();
instead of
var username = = $("#uname").val();
You can't have = =, it's a syntax error.
Also, make sure you properly 'escape' $("#username").val().
If someone enters: myname&action=dosomethingelse I'd give it a fair change it will dosomethingelse.
New answer:
$("#signup").validate( {
var username = $("#username").val(); // -- this is wrong
rules: {
Username: {
required: true,
...
});
You can fix this the easy way by just not declaring the variable at all since you're only using it is one place, but that's no fun :D
The solution is a closure:
$("#signup").validate( (function () {
var username = $("#username").val();
return {
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
}
},
submitHandler: function(form) {
form.submit();
}
};
}()));
(I haven't tested it, there may be a typo or syntax error).
If you have no idea what this does or why, don't worry about it :D