Login form submit button does not work - javascript

I've created a simple one word password login using PHP. The password is stored in the php file - I know this isn't massively secure but all I want is for people to not be able to wander into the site.
For the sake of testing the password is password
You can see that I have a jQuery shake effect when it is wrong.
My Question:
Why does my submit button not work with the correct password on hitting the submit button and why does hitting return behave differently to the submit button?
My code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/vibrate.js"></script>
</head>
<body>
<!-- body content -->
<div class="wrapper">
<!-- container -->
<div class="container">
<div class="col-lg-12">
<div id="login" class="form-wrapper content-flood">
<form action='php/login.php' method="post" class="login-form" id="loginform">
<h3 class="text-center">Enter your password:</h3>
<input type="password" name="password">
<input type="button" name="Submit" id="submit_butt" value="Submit" formaction="php/login.php"/>
</form>
</div>
</div>
</div>
<!-- end container -->
</div>
<!-- end body content -->
<script type="text/javascript">
$(document).ready(function() {
$("#submit_butt").click( function() {
// configurations for the buzzing effect. Be careful not to make it too annoying!
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Oops, wrong password!</p>');
// clear the fields to discourage brute forcing :)
$("#pwd").val("");
});
});
</script>
</body>
</html>
PHP:
<?php
// this password may come from any source.
// it's a variable for the sake of simplicity
$password = 'password';
if($_POST['password'] == $password){
$_SESSION["userid1"] = $id1;
header("Location: ../home.html"); // redirects
}else{
}
?>
Javascript:
jQuery.fn.vibrate = function(conf) {
var config = jQuery.extend({
speed: 30,
duration: 2000,
frequency: 10000,
spread: 3
}, conf);
return this.each(function() {
var t = jQuery(this);
var vibrate = function() {
var topPos = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);
var leftPos = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);
var rotate = Math.floor(Math.random() * config.spread - (config.spread - 1) / 2); // cheers to erik#birdy.nu for the rotation-idea
t.css({position: 'relative', left: leftPos +'px', top: topPos +'px', WebkitTransform: 'rotate(' +rotate +'deg)', WebkitTransform: 'rotate(0deg)'});
};
var doVibration = function () {
var vibrationInterval = setInterval(vibrate, config.speed);
var stopVibration = function() {
clearInterval(vibrationInterval);
t.css({position: 'static'});
};
setTimeout(stopVibration, config.duration);
};
/*
Mofication by Kishore - I am commenting out the following line as it calls the vibration function repeatedly.
We need to call it only once. So, instead I make a call to doVibration() directly.
*/
//setInterval(doVibration, config.frequency);
doVibration();
});
}
;
EDIT: I'm leaving 'else' in the PHP empty becuse the jQuery is handling the error?
I couldn't get a JSFIDDLE of this working but here is the site in action (which is also a test version).
http://hea.getevent.info/

Use input type Submit instead of Button
like
<input type="submit" name="Submit" id="submit_butt" value="Submit" formaction="php/login.php"/>
Else you can use input type button and Submit form using AJAX.

Instead of attaching the listener to the submit button you should register a listener on the submit action of the form. That way you can capture both the submit button click (once it has changed to a submit button as the other questions have stated) and somebody just hitting enter on their keyboard:
$(".login-form").on("submit", function(e)
{
// Stop the form submitting
e.preventDefault();
// Do your checks for errors
// If there are none
$(this)[0].submit();
});

Your server returns a HTTP 302 instead of a HTTP 200. And I was able to log in, but I did see shaking and an Oops ... basically due to poor logic.
Remote Address:212.48.79.185:80
Request URL:http://hea.getevent.info/php/login.php
Request Method:POST
Status Code:302 Moved Temporarily
Request Headersview source
And your logic does not look quite right, unless I am missing something. We cannot see your ajax but the following statements need to be in the success callback of the ajax call. Both enter and button click worked the same for me. The code below is fired too early, before your ajax call is complete, AND you also do not prevent default form submission, so it submits too .... twice.
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Oops, wrong password!</p>');
And you need to prevent default so that you can do the submit yourself after you confirm the password:
$("#submit_butt").click( function(e) {
e.preventDefault();
.......
});

You're not submitting the form, that's why its not doing the authentication
You could just change your input type from button to submit:
<input type="submit" name="Submit" id="submit_butt" value="Submit" formaction="php/login.php"/>
or just submit the form in your click event:
$("#submit_butt").click( function() {
.
.
.
$("#loginform" ).submit();
}

Related

Event listener for successful Captcha verification

I've added a Re captcha v2 into my site and I want to call a function after it's successfully solved,
so far my code looks like this:
<body>
<div style='visibility: hidden;position:absolute;' class="g-recaptcha" data-sitekey="6Lf2yr4aAAAAAPt4qOYdNAJPAB53lCkcDn">
</div>
<button id='submit' onclick="show_captcha()">Submit data</button>
<div id="stat"></div>
<script>
function show_captcha() {
var btn=document.querySelector('#submit');
var cap=document.querySelector('.g-recaptcha');
btn.style.visibility='hidden';
btn.style.position='absolute';
cap.style.visibility='visible';
cap.style.position='relative';
}
document.querySelector('.g-recaptcha').addEventListener('change', (event) => {
console.log('here');
var cap=document.querySelector('.g-recaptcha');
data=['xyz',document.querySelector('#g-recaptcha-response').value.toString()];
if(cap.value=='')
return;
//function after captcha is solved goes here
});
</script>
</body>
the change event listener isn't working, so how can I achieve what I want?
Try to configure reCAPTCHA with a callback on successful validation. Have a look at ReCaptcha v2 client side events

Fill different data of the same form multiple times and auto submit to google sheet

I have one some data need transfer to array, and send it to google sheet
Data look like below
-|PO: 2005 |
12121211212121,| Qty: 45|
BIN:110|
eBay| 11/6/2017-|
PO: 2165 |
333333333,| Qty: 54|
BIN:20|
google| 11/6/2017-|
First I user JS transfer to array, and I put all data from array to form, and click submit form.
Array like
(6) ["PO: 2005 ", " 12121211212121,", " Qty: 45", " BIN:110", " eBay", " 11/6/2017"]
index.html:62
(6) [" PO: 2165 ", " 333333333,", " Qty: 54", " BIN:20", " google", " 11/6/2017"]
The form should be submitted multiple times, but on the google sheet I only got the data for the first one
This is my main HTML
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//
$(document).ready(function() {
//
$('#googleSheetInsert').bootstrapValidator({
//submitButtons: '#postForm',
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
var url = ' ';
var redirectUrl = 'index.html';
// show the loading
$('#postForm').prepend($('<span></span>').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate'));
var jqxhr = $.post(url, $form.serialize(), function(data) {
console.log("Success! Data: " + data.statusText);
// $(location).attr('href',redirectUrl); relocation
})
.fail(function(data) {
console.warn("Error! Data: " + data.statusText);
// HACK - check if browser is Safari - and redirect even if fail b/c we know the form submits.
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
//alert("Browser is Safari -- we get an error, but the form still submits -- continue.");
$(location).attr('href',redirectUrl);
}
});
});
});
<html>
<head>
<title>Getting Started Extension's Popup</title>
<link href="http://cdn.jsdelivr.net/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="http://cdn.jsdelivr.net/fontawesome/4.1.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="http://cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/css/bootstrapValidator.min.css"/>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.bootstrapvalidator/0.5.0/js/bootstrapValidator.min.js"></script>
<style type="text/css">
body {
margin: 10px;
white-space: nowrap;
}
h1 {
font-size: 15px;
}
#container {
align-items: center;
display: flex;
justify-content: space-between;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script>
function submitDataToGoogleSheet(){
var dataFromInput = document.getElementById("SOS_POData").value;
// Split by -| and put to array
var filter0 = dataFromInput.split("-|");
// Remove Empty Element
var unitArray =[];
for(var i=0;i<filter0.length;i++){
if(filter0[i]!==""){
unitArray.push(filter0[i].split("|"));
}
}
// insert data to google sheet
for(j=0;j<unitArray.length;j++){
doSubmite(unitArray,j);
}
}
function doSubmite(unitArray,j){
console.log(unitArray[j]);
document.getElementById('PO_Number').value = ((unitArray[j][0]).substring(4)).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('Part_Number').value = (unitArray[j][1]).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('Qty').value = ((unitArray[j][2]).substring(5)).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('BIN').value = (unitArray[j][3]).substring(5);
document.getElementById('Receiver_Name').value = (unitArray[j][4]).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('Receiver_Data').value = (unitArray[j][5]).replace(/(^\s*)|(\s*$)/g,"");
document.getElementById('postForm').click();
}
</script>
</head>
<body>
<h1>Please copy all information from laeb in there.</h1>
<div id="container">
<form id="dataFromSOS" action="#" method="post">
<input type="text" name="SOS_POData" id="SOS_POData" required="" placeholder="Please copy all label information in there">
<input type="button" name="submit_form" value="Submite" onclick="submitDataToGoogleSheet()">
</form >
</div>
<div>
<form id="googleSheetInsert">
<label>PO</label>
<input id='PO_Number' name='PO_Number' type='text'>
<label>PartNumber</label>
<input id='Part_Number' name='Part_Number' type='text'>
<label>Qty</label>
<input id='Qty' name='Qty' type='text'>
<label>BIN</label>
<input id='BIN' name='BIN' type='text'>
<label>Receiver_Name</label>
<input id='Receiver_Name' name='Receiver_Name' type='text'>
<label>Receiver_Data</label>
<input id='Receiver_Data' name='Receiver_Data' type='text'>
<input type="submit" name="submit" id="postForm" />
</form>
</div>
<script src="js/sendDataToGoogleSheedAjax.js"></script>
</body>
</html>
Did you set up the Google Sheet to handle your forms being submitted at the same time?
You might follow the below example:
https://medium.com/#dmccoy/how-to-submit-an-html-form-to-google-sheets-without-google-forms-b833952cc175
As far as your multiple submits, they seem to be working as far as I can tell (without a sheet to submit to). If I step through the code I can see the form being updated with the values and everything seems parsed okay. Which is what leaves me to believe the problem is on the receiving side.
To get it to work for me I did the following:
Have your names in the google sheet columns and form <input name=""> match.
In your google sheets go to Tools->Script editor and insert the script from here: https://gist.github.com/mhawksey/1276293
In the script editor Do Run->Run Function->setup
In the script editor Do Publish->Deploy as web app...
set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
Be sure to note the url as that's what we will POST to
It should look like https://script.google.com/macros/s/<GIBERISH>/exec
Update how you call the ajax POST function (I couldn't get the bootstrap validator to work. In fact it was causing only 1 POST to be sent, so I just removed it and everything functions as expected.)
Code:
$('#googleSheetInsert').on('submit', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Use Ajax to submit form data
var url = 'https://script.google.com/macros/s/<GIBERISH>/exec';
var redirectUrl = 'index.html';
// show the loading
$('#postForm').prepend($('<span></span>').addClass('glyphicon glyphicon-refresh glyphicon-refresh-animate'));
var jqxhr = $.post(url, $form.serialize(), function(data) {
console.log("Success! Data: " + data.statusText);
// $(location).attr('href',redirectUrl); relocation
})
.fail(function(data) {
console.warn("Error! Data: " + data.statusText);
// HACK - check if browser is Safari - and redirect even if fail b/c we know the form submits.
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
//alert("Browser is Safari -- we get an error, but the form still submits -- continue.");
$(location).attr('href',redirectUrl);
}
});
});
Images Showing the working code:
Submitting your test data a couple times
Form updated

PHP not working on js form

I have a form on my website(http://hokuco.com/test/). It creates a folder with php, but ever since I installed a javascript my php is not working. The javascript redirects to the folder the php creates. Ironically, before I made the javascript work, the php works.
focus on the area between the two barriers that look like this:
<!--===========-->
index.php:
<?php
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
$src = "./xe7";
$dst = $_POST['foldername'];
recurse_copy($src,$dst);
?>
<link rel="stylesheet" type="text/css" href="style.css" />
<div>
<body onload="timer=setTimeout('removeControls();',3)">
<h1>Drawblog</h1>
<div class="FAQ" style ="box-shadow: 1px 1px 3px rgba(0,0,0,0);">
Controls
-
<div class="list" style ="box-shadow: 1px 1px 3px rgba(0,0,0,0);">
<!--===========-->
<form method="post" id ="form" action ="index.php">
<input type="text" name="foldername" id ="togl">
<input type="submit" name="submit" value="Create panorama">
<script type="text/javascript">
window.onload = function () {
document.getElementById("form").onsubmit = function () {
var folder = document.getElementById("togl").value;
window.location.href ="http://hokuco.com/test/" + folder + "/toggle.php";
return false;
}
}
</script>
</form>
<!--===========-->
<h3>Or,</h3>
<h2>Login with an access code(the account you just typed into the box above, or a code someone shared with you)</h2>
<input type="text" id="field" />
<button id="submit">Go</button>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
document.getElementById("submit").addEventListener("click", function(){
var folder = document.getElementById("field").value;
var url = "http://hokuco.com/test/" + folder + "/index.html";
window.location.href = url;
});
</script>
</div>
</div>
<h1> </h1>
<h1> </h1>
<p>make shocking panoramas in minutes, no account needed</p>
<br/>
<br/>
<br/>
<br/>
<p>special thanks to:</p>
<div id="info">three.js css3d - panorama.</div>
<h5>a hokuco company</h5>
</div>
You are redirecting the user when the on-submit button is pressed. This happens instead of submitting the form.
If you want to submit the form, wait till it's work is done, and then redirect the user to the new location, you could use AJAX to submit the form, and a callback to redirect the user once it's done. See this: submit the form using ajax
Alternatively you could just use a php redirect in the page form submits to, and send the user there. Since this page is both the form and the submit target you could use something like:
if (isset($_POST['foldername'])) {
$dst = $_POST['foldername'];
recurse_copy($src, $dst);
$destURL = "http://hokuco.com/test/".$dst."/toggle.php";
header('Location: '.$destURL);
die('redirecting, please wait. Alternatively use this url: '.$destURL);
}
This is very rudimentary and dangerous, since you are not cleaning the user input for the folder name (See this: Regular expression for folders), however it may help you understand the concept, in order to get to the next step.
<form method="post" id ="form" action ="index.php">
<input type="text" name="foldername" id ="togl">
<input type="submit" name="submit" value="Create panorama">
</form>
Alright. Before you added JS code, your form used to be submitted to index.php when the user pressed the submit button.
However, now you have added a handler to onsubmit event for this form.
<script type="text/javascript">
window.onload = function () {
document.getElementById("form").onsubmit = function () {
var folder = document.getElementById("togl").value;
window.location.href ="http://hokuco.com/test/" + folder + "/toggle.php";
return false;
}
}
</script>
Note that your handler returns false, thus suppressing the default behaviour of form submission. Indeed, it needs to return false to be able to perform redirection.
However, now that you've introduced your own onsubmit handler, you need to provide your own custom JavaScript code to submit form. One way to do so, using jQuery, is like this:
<script type="text/javascript">
window.onload = function () {
document.getElementById("form").onsubmit = function () {
// Submit form to index.php
$.post('index.php', $('#form').serialize(), function() {
// Perform redirection, once submission succeeds
var folder = document.getElementById("togl").value;
window.location.href ="http://hokuco.com/test/" + folder + "/toggle.php";
});
return false;
}
}
</script>
You might also want to consider removing JS handler altogether and instead implementing redirection logic in PHP.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

I have a simple contact form in aspx.
I want to validate the reCaptcha (client-side) before submitting the form.
Please help.
Sample code:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Form</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
$("#cmdSubmit").click(function () {
//need to validate the captcha
});
</script>
</head>
<body>
<form id="form1" runat="server">
<label class="clsLabe">First Name<sup>*</sup></label><br />
<input type="text" id="txtFName" name="txtFName" class="clsInput" /><br />
<div class="g-recaptcha" data-sitekey="my_key"></div>
<img id="cmdSubmit" src="SubmitBtn.png" alt="Submit Form" style="cursor:pointer;" />
</form>
</body>
</html>
I want to validate the captcha on cmdSubmit click.
Please help.
This Client side verification of reCaptcha - the following worked for me :
if reCaptcha is not validated on client side grecaptcha.getResponse(); returns null, else is returns a value other than null.
Javascript Code:
var response = grecaptcha.getResponse();
if(response.length == 0)
//reCaptcha not verified
else
//reCaptch verified
Use this to validate google captcha with simple javascript.
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this) method form button:
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
If you render the Recaptcha on a callback
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
using an empty DIV as a placeholder
<div id='html_element'></div>
then you can specify an optional function call on a successful CAPTCHA response
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key',
'callback' : correctCaptcha
});
};
The recaptcha response will then be sent to the 'correctCaptcha' function.
var correctCaptcha = function(response) {
alert(response);
};
All of this was from the Google API notes :
Google Recaptcha v2 API Notes
I'm a bit unsure why you would want to do this. Normally you would send the g-recaptcha-response field along with your Private key to safely validate server-side. Unless you wanted to disable the submit button until the recaptcha was sucessful or such - in which case the above should work.
Hope this helps.
Paul
Simplified Paul's answer:
Source:
<script src="https://www.google.com/recaptcha/api.js"></script>
HTML:
<div class="g-recaptcha" data-sitekey="YOUR_KEY" data-callback="correctCaptcha"></div>
JS:
var correctCaptcha = function(response) {
alert(response);
};
I used HarveyEV's solution but misread it and did it with jQuery validate instead of Bootstrap validator.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script>
$("#contactForm").validate({
submitHandler: function (form) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if (response.length == 0) {
$('#recaptcha-error').show();
return false;
}
//recaptcha passed validation
else {
$('#recaptcha-error').hide();
return true;
}
}
});
</script>
I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
Unfortunately, there's no way to validate the captcha on the client-side only (web browser), because the nature of captcha itself requires at least two actors (sides) to complete the process.
The client-side - asks a human to solve some puzzle, math equitation, text recognition, and the response is being encoded by an algorithm alongside with some metadata like captcha solving timestamp, pseudo-random challenge code.
Once the client-side submits the form with a captcha response code, the server-side needs to validate this captcha response code with a predefined set of rules, ie. if captcha solved within 5 min period, if the client's IP addresses are the same and so on.
This a very general description, how captchas works, every single implementation (like Google's ReCaptcha, some basic math equitation solving self-made captchas), but the only one thing is common - client-side (web browser) captures users' response and server-side (webserver) validates this response in order to know if the form submission was made by a human or a robot.
NB. The client (web browser) has an option to disable the execution of JavaScript code, which means that the proposed solutions are completely useless.
you can render your recaptcha using following code
<div id="recapchaWidget" class="g-recaptcha"></div>
<script type="text/javascript">
var widId = "";
var onloadCallback = function ()
{
widId = grecaptcha.render('recapchaWidget', {
'sitekey':'Your Site Key'
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Then you can validate your recaptcha by using "IsRecapchaValid()" method as follows.
<script type="text/javascript">
function IsRecapchaValid()
{
var res = grecaptcha.getResponse(widId);
if (res == "" || res == undefined || res.length == 0)
{
return false;
}
return true;
}
</script>
Source Link
You can simply check on client side using
grecaptcha.getResponse() method
var rcres = grecaptcha.getResponse();
if(rcres.length){
grecaptcha.reset();
showHideMsg("Form Submitted!","success");
}else{
showHideMsg("Please verify reCAPTCHA","error");
}
I used Palek's solution inside a Bootstrap validator and it works. I'd have added a comment to his but I don'y have the rep;). Simplified version:
$('#form').validator().on('submit', function (e) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if(response.length == 0) {
e.preventDefault();
$('#recaptcha-error').show();
}
//recaptcha passed validation
else {
$('#recaptcha-error').hide();
}
if (e.isDefaultPrevented()) {
return false;
} else {
return true;
}
});
Here's how we were able to validate the RECAPTCHA using .NET:
FRONT-END
<div id="rcaptcha" class="g-recaptcha" data-sitekey="[YOUR-KEY-GOES-HERE]" data-callback="onFepCaptchaSubmit"></div>
BACK-END:
public static bool IsCaptchaValid(HttpRequestBase requestBase)
{
var recaptchaResponse = requestBase.Form["g-recaptcha-response"];
if (string.IsNullOrEmpty(recaptchaResponse))
{
return false;
}
string postData = string.Format("secret={0}&response={1}&remoteip={2}", "[YOUR-KEY-GOES-HERE]", recaptchaResponse, requestBase.UserHostAddress);
byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = "";
using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
return System.Text.RegularExpressions.Regex.IsMatch(responseString, "\"success\"(\\s*?):(\\s*?)true", System.Text.RegularExpressions.RegexOptions.Compiled);
}
Call the above method within your Controller's POST action.
If you just want to avoid a trip to the server when the user hasn't even attempted the reCAPTCHA, put a validate function in the onsubmit action:
<form id="start_game" action="start-game" method="post" onsubmit="return validate_form();">
And then make that function something like this:
function validate_form() {
const recaptcha_box_checked = (grecaptcha.getResponse()) ? true : false;
if (recaptcha_box_checked) {
return true;
}
else {
alert("You must check the 'I am not a robot' box before you can start a game!");
return false;
}
}
Now, the user could certainly subvert this, but your backend is going to check the g-recaptcha-response with a google server using your secret key. This just stops the user from having to go through another page or two when she simply forgets to check the box.
You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.
let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
'callback': function(response) {
recaptchVerified = true;
// reCAPTCHA solved, allow signInWithPhoneNumber.
// ...
},
'expired-callback': function() {
// Response expired. Ask user to solve reCAPTCHA again.
// ...
}
});
Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.
So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.
if (typeof grecaptcha !== 'undefined' && $("#dvCaptcha").length > 0 && $("#dvCaptcha").html() == "") {
dvcontainer = grecaptcha.render('dvCaptcha', {
'sitekey': ReCaptchSiteKey,
'expired-callback' :function (response){
recaptch.reset();
c_responce = null;
},
'callback': function (response) {
$("[id*=txtCaptcha]").val(c_responce);
$("[id*=rfvCaptcha]").hide();
c_responce = response;
}
});
}
function callonanybuttonClick(){
if (c_responce == null) {
$("[id*=txtCaptcha]").val("");
$("[id*=rfvCaptcha]").show();
return false;
}
else {
$("[id*=txtCaptcha]").val(c_responce);
$("[id*=rfvCaptcha]").hide();
return true;
}
}
<div id="dvCaptcha" class="captchdiv"></div>
<asp:TextBox ID="txtCaptcha" runat="server" Style="display: none" />
<label id="rfvCaptcha" style="color:red;display:none;font-weight:normal;">Captcha validation is required.</label>
Captcha validation is required.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript">
function get_action() {
var v = grecaptcha.getResponse();
console.log("Resp" + v);
if (v == '') {
document.getElementById('captcha').innerHTML = "You can't leave Captcha Code empty";
return false;
}
else {
document.getElementById('captcha').innerHTML = "Captcha completed";
return true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="return get_action();">
<div>
<div class="g-recaptcha" data-sitekey="6LeKyT8UAAAAAKXlohEII1NafSXGYPnpC_F0-RBS"></div>
</div>
<%-- <input type="submit" value="Button" />--%>
<asp:Button ID="Button1" runat="server"
Text="Button" />
<div id="captcha"></div>
</form>
</body>
</html>
It will work as expected.

youtube api v3 search by keyword javascript

The javascript example for "search by keyword" that is given at the google developers page isn't working for me. https://developers.google.com/youtube/v3/code_samples/javascript
When I run the code, I get a disabled search box with "cats" inside. Also, the example doesn't explain how to write in the API key as opposed to the Client ID. It says it's possible, but gives no concrete example of how to do it. Can someone point out where this code is going wrong. The code for the two .js files and the html is as follows:
auth.js file:
// The client ID is obtained from the Google Developers Console
// at https://console.developers.google.com/.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
// Upon loading, the Google APIs JS client automatically invokes this callback.
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fails and the
// user interface that prompts for authorization needs to display.
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// http://code.google.com/p/google-api-javascript-client /wiki/GettingStarted#Loading_the_Client
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
});
}
search.js file:
// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
search.html
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="auth.js"></script>
<script src="search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
The documentation is misleading a bit (one might even say incorrect); the HTML for the "search by keyword" is loading the same "auth.js" that the other two examples on that page are, but it doesn't then have any HTML elements to actually trigger the login process (i.e. a "login button" if a user isn't already authorized) like the other two examples do. Bascially, if you're using that provided auth.js, you need to have, in your HTML, a section that looks like this:
<div id="login-container" class="pre-auth">
This application requires access to your YouTube account.
Please authorize to continue.
</div>
Then, you can also add the class of "post-auth" on a new div that wraps around your existing buttons and search container. The demo will then, when a user visits, only present the login link; when clicked on, and when a user allows the authorization, then the login link will be hidden and your search area will be shown (and the button enabled). That's just how the demo is set up.
Of course, search by keyword does NOT require oAuth2, and so (to answer your 2nd question) you might find it easier to A) remove the handleApiLoaded method (so your button is never disabled), and B) call gapi.client.load() manually (i.e. not triggered by an oAuth success). Then, call gapi.client.setApiKey({YOUR KEY}) so that all of your requests will include your key in their header.
Thanks so much jlmcdonald for your help. It took me a while to figure out the second part of your response, but I finally had success. The following html gets the example on the google developers webpage to work. Note though, at first I was getting a 401 error. To fix it, I had to go to the google developers console and select my project. Then, APIs&auth->consent screen and then fill in the email address and product name:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="login-container" class="pre-auth">
This application requires access to your YouTube account.
Please authorize to continue.
</div>
<div id="buttons" class="post-auth">
<label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
</div>
<div id="search-container">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="/files/theme/auth.js"></script>
<script src="/files/theme/search.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
As you noted in your response, oAuth2 isn't necessary for a simple keyword search. The following is some html that just uses the API key. I didn't reference the two .js files like before, rather, I just included the script in the html. Your post at gapi.client.youtube is undefined? really helped me figure it out:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="buttons">
<label> <input id="query" value='cats' type="text"/><button id="search-button" onclick="keyWordsearch()">Search</button></label>
</div>
<div id="search-container">
</div>
<script>
function keyWordsearch(){
gapi.client.setApiKey('API key here');
gapi.client.load('youtube', 'v3', function() {
makeRequest();
});
}
function makeRequest() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
</body>
</html>
Now that I got the search part, could you explain how I can display the thumbnails and titles of the results and then when I click them, the video opens in an embedded player on the same page? Thanks.
Thank you for your coding. Let me share my code:
function makeRequest(){
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response){
var str = JSON.stringify(response.result,'',4);
$('#search-container').val( str);
makeControl(response);
});
}
function makeControl(resp){
var stList = '<table id="res1" border="1" cellspacing="1" width="100%"><tbody>';
for (var i=0; i<resp.items.length;i++){
var vid = resp.items[i].id.videoId;
var tit = resp.items[i].snippet.title;
if(typeof vid != 'undefined'){
stList += '<tr><td style="width:80px;vertical-align:top">'+
'<a class="show" href="#" title="'+ vid + '" onclick="playVid(this);'+
' return false">'+
'<img width="80" height="60" src="http://img.youtube.com/vi/'+
vid +'/default.jpg"></a></td>'+
'<td><b>'+i+'</b>-'+ tit +'</td></tr>';
}
}
document.getElementById('list1').innerHTML = stList + '</tbody></table>';
//HTML: <div id="list1"
//style="width:853px;height:400px;overflow:auto;background-color:#EEEEEE">
//</div>
}
function playVid(thi){
var st = 'https://www.youtube.com/embed/'+thi.title+'?autoplay=1';
document.getElementById('player').src = st;
//HTML: <iframe id="player" width="853" height="480" src="" frameborder="1" allowfullscreen>
//</iframe>
}

Categories