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.
Related
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 am trying to implement the newest ReCaptcha (aka "invisible" ReCaptcha) within an form using jQuery and an "ajax" request.
ReCaptcha documentation: https://developers.google.com/recaptcha/docs/invisible
My form:
<form id="myForm" >
<input type="email" name="email" /><br />
<input type="password" name="password" /><br/>
<!--<input type="submit" value="log in" />-->
<button class="g-recaptcha" data-sitekey="6LdK..." data-callback="onSubmit">log in</button>
</form>
<div id="status"></div>
My javascript (jQuery):
<script>
function onSubmit(token){
document.getElementById("myForm").submit();
}
$(document).ready(function(){
$("#myForm").submit(function(event){
event.preventDefault();
var datas = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "test.php",
data: datas,
dataType: "json",
beforeSend: function(){
$("#status").html("logging in...");
},
success: function(response){
$("#status").html(response.text);
if(response.type=="success"){
window.location.replace("/myaccount");
}
},
error: function(){
$("#status").html("Failed.");
}
});
});
});
</script>
ReCaptcha requires to set a "data-callback", which I am not sure how to bind with my already existing ".submit(function(event)" function.
My "onSubmit()" trick did not work, it ignores the "ajax" and refreshes the page.
How do I send the "g-recaptcha-response" value within my "datas" variable to POST it to test.php?
So here is how I solved it after digging further in Invisible reCAPTCHA's doc, and learning a bit of jQuery obviously since I was not very familiar with JS (cool stuff):
My head tag with the javascript (and a bit of css to remove the ugly Google badge):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=fr" async defer></script>
<style>
.grecaptcha-badge{
display:none;
}
</style>
<script>
var onloadCallback = function(){
grecaptcha.render("emplacementRecaptcha",{
"sitekey": "YOUR_RECAPTCHA_SITEKEY_HERE",
"badge": "inline",
"type": "image",
"size": "invisible",
"callback": onSubmit
});
};
var onSubmit = function(token){
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var userTfaOtp = $("#userTfaOtp").val();
$.ajax({
type: "POST",
url: location.href,
data:{
userEmail: userEmail,
userPassword: userPassword,
userTfaOtp: userTfaOtp,
userJetonRecaptcha: token
},
dataType: "json",
beforeSend: function(){
$("#statutConnexion").html("Traitement de votre requête d'authentification en cours...");
},
success: function(response){
$("#statutConnexion").html(response.Message);
if(response.Victoire){
$("#formulaireConnexion").slideUp();
window.location.replace("/compte");
}
else{
grecaptcha.reset();
}
},
error: function(){
$("#statutConnexion").html("La communication avec le système d'authentification n'a pas pu être établie. Veuillez réessayer.");
grecaptcha.reset();
}
});
};
function validate(event){
event.preventDefault();
$("#statutConnexion").html("Validation de votre épreuve CAPTCHA en cours...");
grecaptcha.execute();
}
function onload(){
var element = document.getElementById("boutonConnexion");
element.onclick = validate;
}
</script>
HTML:
<div id="formulaireConnexion">
<input type="email" name="userEmail" id="userEmail" placeholder="Courriel" title="Courriel" required="required" /><br />
<input type="password" name="userPassword" id="userPassword" placeholder="Mot de passe" title="Mot de passe" required="required" /><br/>
<input type="text" name="userTfaOtp" id="userTfaOtp" placeholder="Double authentification (optionnelle)" autocomplete="off" pattern="[0-9]{6}" title="Six caractères numériques" maxlength="6" /><br />
<div id="emplacementRecaptcha"></div>
<button id="boutonConnexion">Connexion</button>
</div>
<div id="statutConnexion"></div>
<script>onload();</script>
Let me know if you need the whole PHP as well since it's out of the scope of this question. You will probably need to change "url: location.href," within the JS above since in my case the script rendering the HTML form and the JS and dealing with the POST vars is the same (not great, testing purpose). Basically I just verify the POST vars then finally return a json like:
$jsonVictoire = true; // boolean
$jsonMessage = 'anything you want to tell your visitor'; // string
$return =
json_encode(
array(
'Victoire'=>$jsonVictoire,
'Message'=>$jsonMessage
)
);
die($return);
<script defer>
function onSubmit(token) {
var f = $("#myForm");
$.ajax({
type: "POST",
url: "test.php",
data: f.serialize(),
dataType: "json",
beforeSend: function(){
$("#status").html("logging in...");
},
success: function(response){
$("#status").html(response.text);
if(response.type=="success"){
window.location.replace("/myaccount");
} else {
$("#status").html("Captcha failed.");
}
},
error: function(){
$("#status").html("Failed.");
}
});
}
</script>
In test.php you need to verify captcha on server side:
<?php
if(isset($_POST['g-recaptcha-response'])) {
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=[YOUR_SECRET_KEY]&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
if($result['success'] == 1) {
// Captcha ok
} else {
// Captcha failed
}
}
?>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<div id="login_page" class="g-recaptcha" data-size="invisible" data-sitekey="your sitekey" data-callback="login_page"></div>
<script>
window.onScriptLoad = function () {
// this callback will be called by recaptcah/api.js once its loaded. If we used
// render=explicit as param in script src, then we can explicitly render reCaptcha at this point
// element to "render" invisible captcha in
var htmlEl = document.querySelector('.g-recaptcha');
// option to captcha
var captchaOptions = {
sitekey: 'your site key...',
size: 'invisible',
// reference to an actual function
callback: window.onUserVerified
};
// Only for "invisible" type. if true, will read value from html-element's data-* attribute if its not passed via captchaOptions
var inheritFromDataAttr = true;
// now render
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token){
Your ajax code....
}
$("#blog_inquiry").click(function(e){
//var gg = grecaptcha.getresponse();
var token = window.grecaptcha.getResponse(recaptchaId);
// if no token, mean user is not validated yet
if (!token) {
window.grecaptcha.execute(recaptchaId);
return;
}
});
</script>`
I've created two forms and assigned different submit button IDs. But ajax is executing single form every time even if I execute different button for different ajax call. Following is the code:
Form1.
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#monthlyForm").submit();
$.ajax({
url: '/monthlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton').on('click', function (e) {
handler.open({
name:'Monthly',
description:'Monthly Package',
amount:1450
});
e.preventDefault();
});
$(window).on('popstate', function () {
handler.close();
});
</script>
Form2:
<form action='/cancelannual' method='post'><a href="/cancelannual">
<input class='btn genz-light-red'style=";width:50%; background:#FF1744; height:33px;color:white;"type="submit" value="Cancel" /></a></form>
<!-- Custom Button -->
<form id="yearlyForm" action="/yearlycharged" method="post" >
<div class="form-group">
<input type="hidden" id="stripeToken" name="stripeToken" />
<input type="hidden" id="stripeEmail" name="stripeEmail" />
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton1">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#yearlyForm").submit();
$.ajax({
url: '/yearlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton1').on('click', function (e) {
handler.open({
name:'Yearly',
description:'Yearly Package',
amount:9500
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
</script>
If I click on "customButton" it processes yearly subscription if I click on "customButton1" still it processes yearly subscription instead of monthly. Surprisingly when form popups it has the monthly values in it. But after processing database shows Yearly package processed. In my python/flask code without ajax I can process both packages seperately so the problem is not in my views it lies somewhere in Ajax. Please advise
You have two var handler declarations in the global scope - the second hides the first. Name them differently or wrap both code fragments in separate $(document).ready(function() {...});
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 am trying to create a form that has an action to a URL. But it requires ajax submission first and then it should submit to the action.
It should send me an email (within the newsletter.php).
<script type='text/javascript'>
$(function () {
$("#signup").on('submit', function( e, response ) {
if (response.errors == false) {
$.ajax({
type : 'GET',
url : 'newsletter.php',
data: {
name : $('#os0').val(),
email: $('#os1').val()
},
success : function(data) {
$('#subscribe').submit();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// error handling
}
});
return false;
}
return true;
});
});
</script>
HTML
<form name="signup" id="signup" action="" method="GET">
<input type="text" id="os0" name="Email" />
<input class="text" id="os1" type="text" name="cd_FULLNAME" />
<input type="Submit" name="Submit" id="subscribe" value="Subscribe" />
</form>
<script type='text/javascript'>
$(function () {
$("#signup").on('submit', function( e, response ) {
$.ajax({
type : 'GET',
url : 'newsletter.php',
data: {
name : $('#os0').val(),
email: $('#os1').val()
},
success : function(data) {
$("#signup")[0].submit();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// error handling
}
});
return false;
});
});
</script>
Note the difference between $("#signup")submit(); and $("#signup")[0].submit();.