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.
Related
The following code is working fine when the form is submitted correctly with all valid data in the first attempt. If there is any server side error after submitting the form then when user resubmits the form the recaptcha does not reset.
Following is the sample code:
html-form
<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm" method="POST" action="/signup">
<div class="form-group mobile-number">
<input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
autofocus>
<label for="mobile"> Your Mobile no. </label>
</div>
<div class="g-recaptcha"
data-sitekey="{key}"
data-callback="setResponse"
data-badge="inline"
data-size="invisible">
</div>
<input type="hidden" id="captcha-response" name="captcha-response"/>
<button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function setResponse(response) {
document.getElementById('captcha-response').value = response;
submitForm();
}
function submitForm() {
var $form = $("form");
var data = JSON.stringify($form.serializeObject());
var myJsonObject = JSON.parse(data);
data = JSON.stringify(myJsonObject);
$.ajax({
type: "POST",
url: "dummy url",
contentType: "application/json",
xhrFields: {withCredentials: true},
data: data,
success: function (data, textStatus, request) {
// success
},
error: function (xhr, err) {
// logics here
grecaptcha.execute();
setResponse;
}
});
}
</script>
<script>
jQuery(document).ready(function () {
//homepage form
$('form[name="signupForm"]').validate({
onfocusout: function (element) {
$(element).valid();
},
rules: {
mobileNumber: {
required: true,
minlength: 10,
maxlength: 10
}
},
// Specify validation error messages
messages: {
mobileNumber: "A valid mobile number is of 10-digit",
},
//submit handler
submitHandler: function (form) {
submitForm();
}
});
});
</script>
I think the error is in ajax call but not able to figure out why the captcha is not resetting again.
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();
}
});
});
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/>
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;
}
});
I have a form with two buttons
a) Test - on click of the button a javascript function is called to verify a couple of credentials.
b) Create - on click of the button a javascript function is called to save the form.
#Messages("playauthenticate.project.create")
I have a form tag around these two submit buttons with no action.
name, description, accessKey and secretKey are the four fields in the form.
on clicking on the create button, I want to perform jquery validation and then submit the form but the jquery validation submitHandler is not getting called in the javascript function and there are no errors in the Error Console.
When I click on the create button, the create alert is shown and then the form resets and I am able to see all the parameters entered in the URL.
$("create").click(function() {
alert("create ");
$('#projectForm').validate( {
rules: {
name: {
minlength: 6,
required: true
},
description: {
required: true,
description: true
},
accessKey: {
minlength: 10,
required: true
},
secretKey: {
minlength: 15,
required: true
}
},
focusCleanup: false,
wrapper: 'div',
errorElement: 'span',
highlight: function(element) {
$(element).parents ('.control-group').removeClass ('success').addClass('error');
},
success: function(element) {
$(element).parents ('.control-group').removeClass ('error').addClass('success');
$(element).parents ('.controls:not(:has(.clean))').find ('div:last').before ('<div class="clean"></div>');
},
errorPlacement: function(error, element) {
error.appendTo(element.parents ('.controls'));
},
submitHandler: function() {
alert("hello");
var name = $('#name').val();
var description = $('#description').val();
var accessKey = $('#accessKey').val();
var secretKey = $('#secretKey').val();
var dataString = 'name='+ name + '&description=' + description + '&accessKey=' + accessKey+ '&secretKey=' + secretKey;
//alert(dataString);
$.ajax({
type: "POST",
url: "/demo/save",
data: dataString,
success: function(data) {
$('#result').html("<h2>demo created successfully!</h2>");
},
error: function(data) {
$("#result").html("<h2>Error!</h2>");
}
})
}
});
});
JSfiddle - http://jsfiddle.net/NJxh5/3/
Thank you
.validate() is the method for initializing the plugin. It's not a method of testing the form. Testing is automatic.
Therefore, get rid of the click handler. The click event is captured automatically by the plugin. If the form is valid, the submitHandler will fire.
Otherwise, you are doing it properly by placing your ajax inside the submitHandler callback.
$(document).ready(function () {
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
}
});
});
Working DEMO: http://jsfiddle.net/ACdtX/
With two different buttons and actions:
HTML:
<form id="projectForm">
....
<input type="button" class="button" value="TEST" id="test" />
<input type="button" class="button" value="Create" id="create" />
</form>
jQuery:
$(document).ready(function () {
$('.button').each(function () {
$(this).on('click', function () {
var action;
if ($(this).attr('id') == "test") {
action = 'test.php';
} else {
action = 'create.php';
}
$('#projectForm').submit();
});
});
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
$.ajax({
url: action, // determined from click handler above
// ajax options
});
}
});
});