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.
Related
I tried the code from:https://learn.microsoft.com/en-us/linkedin/talent/apply-with-linkedin/apply-with-linkedin-reference-docs - the One Page Flow example.
I put the code in the page where i want to show the button,
but i get an error in console:Error trying to initialize the widget! Error is :origin: error.origin.not.in.api.domains
the code looks like that(my form is in cf7):
<div class="wrap-form">
<?php echo do_shortcode( get_field('form_shortcode',42)) ?>
<div name="widget-holder">
<script type="text/javascript"
src="https://www.linkedin.com/mjobs/awli/awliWidget">
</script>
apply
<script type="IN/AwliWidget"
data-company-job-code="{15}"
data-integration-context="urn:li:organization:i put here my id"
data-mode="BUTTON_DATA"
data-callback-method="onProfileData"
data-api-key=i put here my id
data-allow-sign-in="true">
</script>
</div>
<script>
function onProfileData(profileData) {
var firstnameField = document.getElementsByName('your-fullname"');
var emailField = document.getElementsByName('your-email');
firstnameField.value = profileData.firstName;
emailField.value = profileData.emailAddress;
}
// prefill form with profile data
</script>
</div>
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
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.
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();
}
Suppose I have 2 html files: form.html and confirm.html
form.html just have a text field and a submit button, when you hit submit it will display what you just typed in text field.
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script type="text/javascript">
function display(){
document.write("You entered: " + document.myform.data.value);
}
</script>
</HEAD>
<BODY>
<center>
<form name="myform">
<input type="text" name="data">
<input type="submit" value="Submit" onClick="display()">
</form>
</BODY>
</HTML>
Now I want that when hit submit button it will display entered value in confirm.html. What should I do? I mean what should be in confirm.html and how data from form.html be used in other location, do I need create a separate JavaScript file to store JS function so I can use it in both 2 html files. I am kind of new to all kind of stuff.
Note: No PHP or server side language or anything super here, just 2 html files in my Desktop and I want to test using FireFox.
Thank you!
You can try using localStorage or cookies. Check one of the 2 solutions found below...
1 - If you have HTML5, you can store the content of you input into the localStorage.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
2 - Also, as #apprentice mentioned, you can also use cookies with HTML standards.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Function for storing to cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into a cookie
setCookie("mytext", mytext, 300);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Function for retrieveing value from a cookie
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into a cookie
var mytext = getCookie("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
What you could do is submit the form using a get method (method="get"), and send it to your confirm.html page (action="./confirm.html").
Then, you could use jQuery to retrieve the values from the URL from your confirm.html page.
This website provides a method to do that: http://jquerybyexample.blogspot.com/2012/06/get-url-parameters-using-jquery.html .
Then, all you have to do is call your display() method.
Seams like a fit for persist.js, which will let you save and load data in the user's browser. After including its javascript file, you can save data like this:
var store = new Persist.Store('My Application');
store.set('some_key', 'this is a bunch of persistent data');
And you can later retrieve the saved data in another html page like the following:
var store = new Persist.Store('My Application');
val = store.get('some_key');
You could also, instead of changing the page, change the content of the page. Upon submission just change the page using the innerHtml variable.