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>`
Related
I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help
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 am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});
Hello everyone I am newbie in java-script so i hope you can help me with my issue. So I have the form, it look something like this:
<form method="post">
Field1: <input type="text" name="field1"><br>
Field2: <input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
I need to take data from the form and make xml request, the xml request should look like this
<root>
<header section>
<section>data</section>
</header section>
<data section>
<field1>data</field2>
<field2>data</field2>
</data section>
</root>
After that i have to display xml response on the page.
I made xml request
<script>
$('.button').click( function() {
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
success: function(xml) {
$(xml).find('root').each(function(){
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
But I don't know how to take data from the form and make request. Can you help me with it? Thanks a lot.
// You can use jQuery to build XML document:
function buildXmlFromForm(form) {
var xml = $('<XMLDocument />');
xml.append (
$('<header-section />').append(
$('<section />').text('data')
)
).append (
$('<data-section />').append(
$('<field1 />').text(form.find("input[name='field1']").val())
).append(
$('<field2 />').text(form.find("input[name='field2']").val())
)
);
return xml.html();
}
// you should use POST or PUT method (not GET) to post xml-data to server side
$( "#form1" ).submit(function(event) {
event.preventDefault();
$("#results").append("<ul></ul>");
var xmlString = buildXmlFromForm($(this));
$("#xmlSrc").val(xmlString);
$.ajax({
type: "POST",
dataType: 'xml',
url: 'response.xml',
data: xmlString,
success: function(respData) {
$("<li></li>").html("ok: "+respData).appendTo("#results ul");
console.log(respData);
},
error: function(errorData) {
$("<li></li>").html("error: "+errorData.statusText).appendTo("#results ul");
console.log(errorData);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form1">
Field1: <input type="text" name="field1" value="***v1***"><br/>
Field2: <input type="text" name="field2" value="***v2***"><br/><br/>
<input type="submit" value="Submit">
</form>
<hr/>
<textarea id="xmlSrc" cols="70" rows="5"></textarea>
<div id="results"/>
Try this:
serialize will return formData of current form
You must have unique identifier for your form to be used as querySelector
$('#myForm').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
data: formData,
success: function(xml) {
$(xml).find('root').each(function() {
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm">
Field1:
<input type="text" name="field1">
<br>Field2:
<input type="text" name="field2">
<br>
<input type="submit" value="Submit">
</form>