Form validation in CodeIgniter using AJAX - javascript

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

Related

Invisible google captcha v2 is not working properly

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.

submit button from hidden form refresh the page

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.

Form Validation with Success

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/>

How do i hide a form after submission is succesfull with Ajax/Jquery

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();

submit a form which is loaded on bootstrap popover

how to submit form loaded on the bootstrap popover?
On click on a button ,a form will be loaded on popover & the same form user should be able submit it by pressing ENTER key. check this fiddle
i tried like this but its loaded whole page
$('#popoverId').popover({
html: true,
title: 'Popover Title<a class="close" href="#");">×</a>',
content: $('#popoverContent').html(),
});
$('#popoverId').click(function (e) {
e.stopPropagation();
});
$(document).click(function (e) {
if (($('.popover').has(e.target).length == 0) || $(e.target).is('.close')) {
$('#popoverId').popover('hide');
}
});
//--------------script to to submit form after validation -------------
$(".popover").parent().find('#something').validate({
rules: {
sproject_name: {
minlength: 3,
maxlength: 15,
required: true
}, tooltip_options: {
sproject_name: {placement: 'center', html: true, trigger: 'focus'}
}
},
submitHandler: function(e) {console.log("ajax logi goes here....");
}
});
html code
<h3>Live demo</h3>
<button id="popoverId" class="popoverThis btn btn-large btn-danger">Click to open form</button>
<div id="popoverContent" class="hide">
<form method="post" name="project-forms" id="something"><input class="red-tooltip" id="sadd_project_id" name="sproject_name" type="text" required/></form>
</div>
You need to use .validate inside #popoverId click. Because, you are using it on page load and at that time popover form still not exist. You can see following code and demo for bets understanding;
$('#popoverId').click(function (e) {
e.stopPropagation();
$('#something').validate({
rules: {
sproject_name: {
minlength: 3,
maxlength: 15,
required: true
}
},
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType : 'json'
})
.done(function (response) {
if (response.success == 'success') {
alert('success');
} else {
alert('fail');
}
});
return false;
}
});
});
See working demo here: Demo

Categories