ReCaptcha: How to autosubmit the form when the captcha was send - javascript

I want to use ReCaptcha to load some extra data on the page. I want the form to be auto submitted when the ReCaptcha was entered. So that I don't need the extra submit button. The problem is that recaptcha loads its content inside an iframe, so its a bit difficult.
At the moment I have this form:
<form action="javascript:getInfo(grecaptcha.getResponse(widget1));" >
<div id="captcha"></div>
<br>
<input type="submit" value="Submit">
</form>
How do I get something like an Event-Listener on the recaptcha submit which submits the outer form?

That's sounds like an interesting technique. It would cut down on the clicking and key strokes for the user. Here is how you could do that, by listening for the successful captcha response you would be able to follow up with the desired action. Here is an example and some documentation. https://developers.google.com/recaptcha/docs/display#example
var RC2KEY = 'sitekey';
function reCaptchaVerify(response) {
if (response === document.querySelector('.g-recaptcha-response').value) {
document.forms['form-name'].submit();
}
}
function reCaptchaExpired() {
/* do something when it expires */
}
function reCaptchaCallback() {
grecaptcha.render('id', {
'sitekey': RC2KEY,
'callback': reCaptchaVerify,
'expired-callback': reCaptchaExpired
});
}
<script src='https://www.google.com/recaptcha/api.js?onload=reCaptchaCallback&render=explicit'></script>

Use # instead of ?
? is used to begin query strings and will mess with method=GET type responses. # is the anchor symbol and will work.

Related

Getting an Ajax response from a form.submit() to PHP

I'm trying to combine a form.submit() call with a jquery/ajax call to get a response from my php login script - I've just spent a few hours trying to hack together some of the hundreds of posts/examples on a similar topic but am out of ideas now so am hoping someone can help.
My sign in form looks like this...
<form id ="signInForm" action= "/userManagement/proxy_process_login.php" method="post" name="login_form">
<input required id="signInUserId" name="email" type="text" placeholder="Username/Email" class="input-medium">
<input required id="signInPassword" name="password" type="password" placeholder="Password" class="input-medium">
<button id="signin" name="signin" class="btn btn-success" onclick="signInSubmit(this.form, this.form.signInPassword);">Sign In</button>
</form>
The function signInSubmit() (called by the button's onclick) simply validates the text fields, and replaces the plain text password with a hashed version before finally calling "form.submit()", like this...
//ommited a bunch of text input validation
var p = document.createElement("input");
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
password.value = ""; // Make sure the plaintext password doesn't get sent.
form.submit();
My PHP script (proxy_process_login) also works fine before adding any jquery/ajax and essentially does this...
if (login($email, $password, $mysqli) == true) {
// Login success (ok to reload existing page)
header("Location: ../index.php?login=success");
exit();
} else {
// Login failed (do NOT want to reload page - just message "fail" back via AJAX so I can update page accordingly)
echo "fail";
exit();
}
But given the route I'm taking to submit the form, I'm struggling to incorporate an Ajax example - because I've got this new "form" variable (with the hashed p variable appended), so I can't use an Ajax call which refers back to the form using jquery like this...
$.ajax({type:'POST', url: '/userManagement/proxy_process_login.php', data:$('#signInForm').serialize(), success: function(response) {
console.log(response);
}});
(because the jquery reference doesn't include the new variable, and I've already specified the php script in the action attribute of my form)
And I also can't call something like "serialize()" on my "form" variable inside signInSubmit().
Any ideas on an appropriate way to structure a solution to this?! Thanks!
Unfortunately there is no callback for native form submission using action attribute , it was used in the past to redirect you to that page and show the results there.
Modern method now is to use ajax call , after perventingthe default submission.
Solution:
HTML:
<form id="myForm">
<!-- form body here --!>
</form>
Javascript:
$("#myForm").submit(function(e){
e.preventDefault();//prevent default submission event.
//validate your form.
//disable your form for preventing duplicate submissions.
//call you ajax here.
//upon ajax success reset your form , show user a success message.
//upon failure you can keep your fields filled , show user error message.
})
this is a typical algorithm i use in any project i do , i recommend using parsley JS for front-end validation.

How can I hide a form after submission with JavaScript?

So I have these forms:
django template:
{% for F in forms %}
<input type="text" name="name/>
<input type="number" name="number/>
<input type="submit" class="button" [onclick="this.disabled=true,this.form.submit(); ??]> #how can I make this work?
{%endfor%}
What the template code does is render out multiple forms based on the value of forms> I want the user to submit the form and then have the form either disappear(preferable) or at least disabled so that they can resubmit. How can I do this?
If you have multiple forms on the page and want to handle them with JavaScript, I would suggest you to use jQuery. You could make something like:
$('input[type="submit"]').click(function() {
// here comes your logic
// and the next line removes the corresponding form
$(this).parents('form').remove();
});
But as Marc B pointed out, you should submit the form via Ajax. I don't know what do you intend to do with the user input, but if you want to use Ajax then you could make something like:
$('form').submit(function() {
$.ajax({
// your logic
});
});
Check the official documentation of jQuery for more details and adapt the examples to your needs.
EDIT:
if you want to prevent the form from submitting and refreshing the page, please change it slightly to:
$('form').submit(function(event) {
$.ajax({
// your logic
});
event.preventDefault();
});

JQuery Validation remote JSFiddle

I have a problem with jquery validation remote and my form submit.
Look this code http://jsfiddle.net/35cHS/135/
<form id="fail">
<label>Documento:</label>
<input id="numero_documento" maxlength="2" name="numero_documento" maxlength="16" type="text" />
<input type="submit" value="Próximo" />
</form>
$('document').ready(function () {
$('#fail').validate({
rules: {
numero_documento: {
required: true
,remote: {
url: 'http://cep.correiocontrol.com.br/04676090.json',
success: function (data) {
//console.log('Ok! Continue submit...');
}
}
}
}
});
});
When I insert a value and click on button it is ok. A submit is called.
But if I uncomment the remote and again insert a value and click ok nothing happens.
I want continue with my form submit because I just want to make a search and return yes or no later.
Is it possible ?
sorry for my english I am working on it =)
remote is a bit misleading because it really just means another file on your server so in this particular case, you can't do a cross domain request to retreive that json object unless you're using json with padding. At this moment, CORS is restricting you. Instead, create a php file on your server, such as, get_json.php, and then use
echo file_get_contents('http://cep.correiocontrol.com.br/04676090.json');
The server will not be limited by CORS unless the configuration on cep.correiocontrol.com.br is configured in such a way to deny these requests completely.

Submit form without page reloading, and link to javascript

I have made a system that when you enter a specific value, it'll fade in values based on the selection.
I have this code here which is the main form where you can input the specific model numbers into the form and then press enter.
<form>
<input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$"
title="Your Model Number." placeholder="Please Input a Model number" size="35" maxlength="8">
<center><span class="egsmall"><strong>Eg: PIV13RT, PIV13RT2, Ect.</strong></span></center>
<center><div class="btnwrap"><input name="proceed" type="submit" class="submitsup" id="forward" /></div></center>
</form>
The problem is that when you press enter, because it's inside of a form, it reloads the page, which means that the fade in won't load because it's reloading the page.
$("#forward").click(function(){
$.ajax({
}).done(function() {
$('.optionbk').fadeIn('slow');
});
});
I realise that this can also be done with Javascript, but that wouldn't allow me to use a Form.
$("#forward").click(function(){
var text = $("#ModelNumber").val();
var comparingText = "PIV13RT";
var comparingText2 = "PIV13RT2";
var comparingText3 = "PIV13RT3";
if (text == comparingText) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText2) {
$('.optionbk').fadeIn('slow');
}
if (text == comparingText3) {
$('.optionbk').fadeIn('slow');
}
});
Is there anyway that I can do it inside of a form, but make it so that the page doesn't reload itself so that the fade works instead of reloading. The form is needed because it is following that specific pattern. Please note that the form isn't linking to an external PHP file.
The quickest solution is to add onsubmit="return false" into your opening <form> tag.
You should bind your callback function to the submit event that the form dispatches and make it return false to cancel the actual submission.
$('form').bind('submit', function(){
$.ajax();
return false;
});

How can I submit a form automatically (onevent) with javascript?

I'd like to be able to submit a form automatically on an event ( a generic form, for user tracking).
For example, create a POST to
http://www.example.com/index.php?option=track&variable=variable
application/x-www-form-urlencoded with stuff like
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2
The actual string will be preformatted, though, because all it is is like a 'ping'.
It needs to be submitted onevent, with external js ( http://example.com/scripts/js.js )
What the hay should I do? This is getting annoying.
Update: I guess I didn't really make myself clear; I have a premade form that isn't supposed to display on the page; it needs to submit on an event. The form fields do not exist on the page; all I do is link to the script on the page and it executes onLoad.
POST uri: http://www.example.com/index.php?option=track&variable=variable
The arguments above (option=track and variable=variable) are not the form details (postdata).
The content type is application/x-www-form-urlencoded , and has the following keys/values.
username=usernamestring
otherdata=otherdata_string
otherdata2=otherdata string 2 (when encoded, the spaces get turned to %20's.)
I need a script that submits this when run.
You have to get the form object and call the submit(); function provided by HTMLFormObject.
document.getElementById('myForm').submit();
1) with the following, (while page is loaded), the form will be immediately autosubmited
<form action="post.php" name="FNAME" method="post">
<input type="text" name="example22" value="YOURVALUE" />
<input type="submit" />
</form>
<SCRIPT TYPE="text/JavaScript">document.forms["FNAME"].submit();</SCRIPT>
another formSubmit alternative - submits any script:
document.forms[0].submit();
2) or use button click after 2second:
<SCRIPT TYPE="text/JavaScript">setInterval(function () {document.getElementById("myButtonId").click();}, 2000);</SCRIPT>

Categories

Resources