Recaptcha image challenge always occurs in Microsoft Edge after form submission (Invisible recaptcha) - microsoft-edge

I've just implemented invisible recaptcha into a web form. Everything works fine with Chrome. But with Microsoft Edge, the image challenge always occurs with every form submission. Which is embarrassing for the users of the website. An idea?
Thanks a lot for your insights and advice :o)
Laurent
Javascript code:
window.onScriptLoad = function () {
var htmlEl = document.querySelector('.g-recaptcha');
var captchaOptions = {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'size': 'invisible',
'badge': 'inline',
callback: window.onUserVerified
};
var inheritFromDataAttr = true;
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token) {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data : {
'lastname' : $("#lastnameField").val(),
'firstname' : $("#firstnameField").val(),
'city' : $("#cityField").val(),
'postalCode' : $("#postalcodeField").val(),
'g-recaptcha-response' : token
},
success:function(data) {
// informs user that form has been submitted
// and processed
},
error: function(xhr, textStatus, error){
// informs user that there was a problem
// processing form on server side
}
});
};
function onSubmitBtnClick () {
window.grecaptcha.execute;
}
HTML code:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<script type="text/javascript" src="js/petition.js"></script>
...
</head>
<body>
<form id="petitionForm" onsubmit="return false;">
<input id="lastnameField" type="text" name="lastname" placeholder="Lastname" required value="Doe">
<input id="firstnameField" type="text" name="firstname" placeholder="Firstname" required value="John">
<input id="postalcodeField" type="text" name="postalCode" placeholder="Postal Code" required value="ABCDEF">
<input id="cityField" type="text" name="city" placeholder="City" value="Oslo">
....
<input type="submit" name="login" class="g-2" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxx" id="signButton" data-callback='' value="Signer" onclick="onSubmitBtnClick();">
<div class="g-recaptcha" id="recaptchaElement" style="align-content: center"></div>
</form>
...
</body>
</html>

Related

Post to zapier webhook and write to spreadsheet

I am trying to use a zapier webhook to write to a google spreadsheet. Here is the simple html I am using:
<form id="my-form">
<input type="text" id="name" name="name" placeholder="Name" />
<input type="text" id="age" name="age" placeholder="Age" />
<input type="text" id="location" name="location" placeholder="Location" />
<input type="text" id="date" name="date" placeholder="Date" />
<button type="submit">Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'https://hooks.zapier.com/hooks/catch/2366642/xxx/',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#response pre').html( data );
console.log(data)
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#my-form').submit( processForm );
})(jQuery);
</script>
When I hit the submit button I am getting the test data that I entered into the initial zap being written to the spreadsheet each time. I am wanting the name, age, location and date fields to be written to the spreadsheet instead
I used this tutorial to get started so I suspect I am getting the data from the form to the ajax request properly. Any help appreciated.
In case anyone else runs into this, I had not selected the fields in the Action portion of the zap. Here is an image. Hope it helps others out:

Google reCaptcha get response

According to this example (https://developers.google.com/recaptcha/docs/display#example) by google
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
I should receive response message and get the alert it but when I try it doesn't display any response and even doesn't call method verifyCallback
I should receive a response after widget rendering, right?
I think you have nothing that causes the grecaptcha.render(... to run.
It needs to be in a handler so that something causes it to run.
verifyCallback should then run as you have correctly specified in the callback parameter
Your callback name should match the callback name passed to the API:
<script type="text/javascript">
var onloadCallback = function(response) {
alert(response);
};
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>

How to prevent redirect to new page on form submit

I am trying to upload a form containing multiple files to my server, request is going to correct Action and I am also getting some data but all the files are coming with null values.
var file = function(){
this.submitForm = function () {
$("#addBrtForm").ajaxSubmit(function (response) {
if (response === "Barter Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-afterUpload");
t.somefunction();
} else {
alert("Try Again!! Barter Not Uploaded");
}
});
};
};
hm.files = new file();
//other thing that I tried
$(function(){
$('#addBrtForm').ajaxForm({
type: 'POST',
beforeSubmit: function () {
return false;
},
success: function (response) {
return false;
if (response === "Barter Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-barter");
t.setBarterpageTitle('My Barter');
} else {
alert("Try Again!! Barter Not Uploaded");
}
}
});
});
<form method="post" action="http://localhost:xxxx/Mobile/Home/FileUpload" enctype="multipart/form-data" data-ajax="false" id="addBrtForm" name="addBrtForm" >
<input type="text" name="Title" data-role="none" />
<input type="text" name="Description" data-role="none" />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="file" name="files" data-role="none" multiple />
<input type="Submit" name="" value="submit" data-role="none" multiple />
<input type="Button" name="" value="submit" data-role="none" multiple onclick="hm.files.submitForm()"/>
</form>
It is working perfectly without "ajaxSubmit" but page is redirecting to "http://localhost:xxxx/Mobile/Home/FileUpload", I don't want that page to come up, I just wanted to catch my response and do something based on that
My controller
public ActionResult FileUpload(FormCollection fc, List<HttpPostedFileBase> files)
{
//some functionilty to save data working perfectely
return Json(SuccesMessage, JsonRequestBehavior.AllowGet);
}
*Note - as I am using jquery mobile so there is no views in my project
thanks to accepted answer on this post and Stephen Muecke for suggesting me to look on that question.
what I did-
removed action attribute from my form tag
used on click instead of submit
used ajax to post data as given in the reference link.
My edited js is shown below
var formdata = new FormData($('#addBrtForm').get(0));
$.ajax({
url: "http://localhost:xxxx/Mobile/Home/FileUpload",
type: 'POST',
data: formdata,
processData: false,
contentType: false,
dataType: "json",
success: function (response) {
if (response === "File Uploaded Successfully") {
alert(response);
$.mobile.changePage("#p-afterUpload");
t.someFunction();
} else {
alert("Try Again!! File Not Uploaded");
}
},
error: function (e) {
alert("Network error has occurred please try again!");
}
});
changed controller action to this -
public ActionResult FileUpload(UploadModel fm, List<HttpPostedFileBase> files)
{
//some functionilty to save data working perfectely
return Json(SuccesMessage, JsonRequestBehavior.AllowGet);
}
- UploadModel is my model having same Name as I used in my form
Add id to the submit button.
<input type="Button" name="" id="submit" value="submit" data-role="none" multiple/>
Then in the javascript do like this
$(function(){
$('#submit').click(function(e){
Do Your stuf here
e.preventDefault();
});
}

.Net MVC - Submitting the form with AngullarJS

I'm pretty new at AngularJS and i'm trying to use it in my new project. I have made an basic login form. When i submit the form, i'm unable to read the values that AngularJS in sending.
Here is my View
<html>
<head>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link href="~/Style/Style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<title>Welcome to Elara!</title>
<script>
var formApp = angular.module('formApp', []);
function formController($scope, $http) {
$scope.formData = {};
$scope.processForm = function () {
$http({
method: 'POST',
url: 'Home/Login',
data: { UserName: $scope.formData.UserName, Password: $scope.formData.Password },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function (data) {
console.log(data);
if (!data.success) {
//do things here
} else {
//do things here
}
});
};
}
</script>
</head>
<body ng-app="formApp" ng-controller="formController">
<div id="FormArea">
<div id="Login" class="well well-sm">
<form role="form" ng-submit="processForm()">
<div class="form-group">
<label for="LoginUserName">User Name</label>
<input type="text" class="form-control" id="LoginUserName" placeholder="Username" ng-model="formData.UserName">
<br />
<label for="LoginPassword">Password</label>
<input form="LoginPassword" type="password" class="form-control" placeholder="Password" ng-model="formData.Password" />
<br />
<button type="submit" class="btn btn-default">Login</button>
</div>
</form>
</div>
<div id="Login">
</div>
</div>
</body>
</html>
And my controller
public bool Login(string UserName, string Password)
{
var userName = UserName;
var password = Password;
return Login(userName, password);
}
The problem is username and password is always null. I'm receiving a string like this from post event
Request.Form = {%7b%22UserName%22%3a%22h%22%2c%22Password%22%3a%22h%22%7d}
You're not really submitting a model, rather 2 arguments, so use params instead of data in your $http request:
$http({
method: 'POST',
url: 'Home/Login',
params: { UserName: $scope.formData.UserName, Password: $scope.formData.Password },
})
Secondly, I hope you're not trying to post this to an MVC controller, post it to a Web API controller instead.

jQuery Mobile and Knockout.js templating, styling isnt applied

Ok so this is beginning to drive me insane. I have for several hours now searched and searched, and every single solution doesnt work for me. So yes, this question might be redundant, but i cant for the life of me get solutions to work.
I have a bunch of checkboxes being generated by a jquery template that is databound via knockout.js. However, it turns up unstyled. Afaik, it is something about jquery mobile does the styling before knockout renderes the template, so it ends up unstyled.
I have tried numerous methods to no avail, so i hope someone here can see what i am doing wrong.
(i am using jquery mobile 1.2.0 , jquery 1.8.2 and knockout 2.2.1)
This is the scripts:
<script type="text/javascript">
jQuery.support.cors = true;
var dataFromServer = "";
// create ViewModel with Geography, name, email, frequency and jobtype
var ViewModel = {
email: ko.observable(""),
geographyList: ["Hovedstaden","Sjælland","Fyn + øer","Nordjylland","Midtjylland","Sønderjylland" ],
selectedGeographies: ko.observableArray(dataFromServer.split(",")),
frequencySelection: ko.observable("frequency"),
jobTypes: ["Kontor (administration, sekretær og reception)","Jura","HR, Ledelse, strategi og udvikling","Marketing, kommunikation og PR","Handel og service (butik, service, værtinde og piccoline)","IT","Grafik og design","Lager, chauffør, bud mv.","Økonomi, regnskab og finans","Kundeservice, telefoninterview, salg og telemarketing","Sprog","Øvrige jobtyper"],
selectedJobTypes: ko.observableArray(dataFromServer.split(",")),
workTimes: ["Fulltid","Deltid"],
selectedWorkTimes: ko.observableArray(dataFromServer.split(","))
};
// function for returning checkbox selection as comma separated list
ViewModel.selectedJobTypesDelimited = ko.dependentObservable(function () {
return this.selectedJobTypes().join(",");
}, ViewModel);
var API_URL = "/webapi/api/Subscriptions/";
// function used for parsing json message before sent
function omitKeys(obj, keys) {
var dup = {};
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (keys.indexOf(key) === -1) {
dup[key] = obj[key];
}
}
}
return dup;
}
//Function called for inserting new subscription record
function subscribe() {
if($("#jobmailForm").valid()=== true){
//window.alert("add subscriptiooncalled");
var mySubscription = ko.toJS(ViewModel);
//var json = JSON.stringify(mySubscription);
var jsonSmall = JSON.stringify(omitKeys(mySubscription, ['geographyList','jobTypes','selectedJobTypesDelimited','workTimes']));
//window.alert(jsonSmall);
$.ajax({
url: API_URL,
cache: false,
type: 'POST',
contentType: 'application/json',
data: jsonSmall,
success: function (data) {
window.alert("success");
},
error: function (error) {
window.alert("ERROR STATUS: " + error.status + " STATUS TEXT: " + error.statusText);
}
});
}
}
function initializeViewModel() {
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
}
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
initializeViewModel();
$('#jobmailDiv').trigger('updatelayout');
});
</script>
<script id="geographyTmpl" type="text/html">
<input type="checkbox" data-role="none" data-bind="attr: { value: $data }, attr: { id: $data }, checked: $root.selectedGeographies" />
<label data-bind="attr: { for: $data }"><span data-bind="text: $data"></span></label>
</script>
<script id="jobTypeTmpl" type="text/html">
<label><input type="checkbox" data-role="none" data-bind="attr: { value: $data }, checked: $root.selectedJobTypes" /><span data-bind="text: $data"></span></label>
</script>
Note, "jobmail" is the surrounding "page" div element, not shown here. And this is the markup:
<div data-role="content">
<umbraco:Item field="bodyText" runat="server"></umbraco:Item>
<form id="jobmailForm" runat="server" data-ajax="false">
<div id="jobmailDiv">
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" class="required email" data-bind="'value': email" />
</p>
<fieldset data-role="controlgroup" data-mini="true" data-bind="template: { name: 'geographyTmpl', foreach: geographyList, templateOptions: { selections: selectedGeographies } }">
<input type="checkbox" id="lol" />
<label for="lol">fkfkufk</label>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<p data-bind="template: { name: 'jobTypeTmpl', foreach: jobTypes, templateOptions: { selections: selectedJobTypes } }"></p>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<input type="radio" id="frequency5" name="frequency" value="5" data-bind="checked: frequencySelection" /><label for="frequency5">Højst 5 gange om ugen</label>
<input type="radio" id="frequency3" name="frequency" value="3" data-bind="checked: frequencySelection" /><label for="frequency3">Højst 3 gange om ugen</label>
<input type="radio" id="frequency1" name="frequency" value="1" data-bind="checked: frequencySelection" /><label for="frequency1">Højst 1 gang om ugen</label>
</fieldset>
<p>
<input type="button" value="Tilmeld" class="nice small radius action button" onClick="subscribe();">
</p>
Tilbage
</div>
</form>
Alternate method of invoking the restyling (doesnt work either):
$(document).on('pagebeforeshow', '#jobmail', function(){
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
});
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
$('#jobmail').trigger('pagecreate');
});
Use a custom binding (Knockout) to trigger jQuery Mobile to enhance the dynamically created content produced by Knockout.
Here is a simple custom binding:
ko.bindingHandlers.jqmEnhance = {
update: function (element, valueAccessor) {
// Get jQuery Mobile to enhance elements within this element
$(element).trigger("create");
}
};
Use the custom binding in your HTML like this, where myValue is the part of your view model that changes, triggering the dynamic content to be inserted into the DOM:
<div data-bind="jqmEnhance: myValue">
<span data-bind="text: someProperty"></span>
My Button
<input type="radio" id="my-id" name="my-name" value="1" data-bind="checked: someOtherProperty" /><label for="my-id">My Label</label>
</div>
In my own case, myValue was part of an expression in an if binding, which would trigger content to be added to the DOM.
<!-- ko if: myValue -->
<span data-bind="jqmEnhance: myValue">
<!-- My content with data-bind attributes -->
</span>
<!-- /ko -->
Every dynamically generated jQuery Mobile content must be manually enhanced.
It can be done in few ways, but most common one can be done through the jQuery Mobile function .trigger( .
Example:
Enhance only page content
$('#page-id').trigger('create');
Enhance full page (header + content + footer):
$('#page-id').trigger('pagecreate');
If you want to find more about this topic take a look my other ARTICLE, to be more transparent it is my personal blog. Or find it HERE.

Resources