My task is to submit a from based on user confirmation. If the user confirm then the form is submitted. If the user deny then the from is redirected to other page. I've a form in jsp like this -
.....
<form id="stageUpdateForm" method="post">
</form>
......
And in javascript I'm trying -
$('#stageUpdateForm').submit(function() {
decision = confirm("Some data changed. Are you sure?");
return decision;
// if user deny then redirect
});
Now if the user deny to submit the from its stay in current page. But I want to redirect the page to other url (eg. - www.google.com) if the user deny. How can I do this?
You want to try something like this:
if (decision) {
window.location = "http://whenever.wherever";
} else {
// Returning false from a submit handler will prevent the submit action.
return false;
}
You can do:
$('#stageUpdateForm').submit(function () {
var decision = confirm('Some data changed. Are you sure?');
// if user deny then redirect
if (!decision) {
$(location).attr('href', 'http://www.google.com');
}
// If user confirm, than it will return true and the form will be sumbited
return decision;
});
Related
I have a submit form, after checking the captcha v3, I need to send the form with the same values. how to do this after receiving the token from the captcha?
With the code below, either a human or a bot outputs to the browser console, but does not redirect to the desired page
.then(result => {
if (result['om_score'] >= 0.5) {
console.log('Human')
} else {
console.log('Bot')
}
});
If i use window.location = "mail.php"; insted of console.log it send empty request
My goal is that the redirect would be to the <from> action with the entered values.
You can use JS to submit the form. Suppose you have the following form:
<form id="myform" action="mail.php" method="post">
....
</form>
You can use JS to submit it:
....
.then(result => {
if (result['om_score'] >= 0.5) {
console.log('Human')
document.getElementById("myform").submit();
} else {
console.log('Bot')
}
});
As a side note, you shouldn't be checking the Captcha client-side because it can easily be spoofed.
I am trying to set up reCaptcha v3 and it sort of works. For some reason the first time I submit the form it fails but from the second submit onwards it is fine. I can't figure out why this is happening?
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('MY_SITE_KEY', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('captcha-response');
recaptchaResponse.value = token;
});
});
</script>
<input type="hidden" name="captcha-response" id="captcha-response">
PHP
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['captcha-response']);
$responseData = json_decode($verifyResponse);
if(!$responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
When I submit the form the first time, I get the validation error but my score is 0.9.
Why you have added "!" with "$responseData->score"? you may need to replace your condition with the following:
Replace this:
if(!$responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
With this one:
if($responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
P.S: Following code takes few seconds to properly load and get a "captcha-reponse" code, so you may need to disable all submit button and wait till you got a "captcha-reponse" to enable the submit button in form or you needs to implementent another way to delay the submit to execute only once you got a "captcha-response" code otherwise you will keep getting "missing-input-response" error message
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('MY_SITE_KEY', {
action: 'contact'
}).then(function(token) {
var recaptchaResponse = document.getElementById('captcha-response');
recaptchaResponse.value = token;
});
});
</script>
You should re-generate the reCaptcha token after error form validation occured.
The token reCaptcha only valid for ONE TIME.
So, you have two options to fixes this issue.
1. Reload the page when error occured
This is the easiest way. You only need to reload the page whenever form validation error occured.
Of course, this will trigger the reCaptcha to generate new token.
2. Handle with AJAX (Non-reload page)
This is the best approach, since this will helps the user not losing the form data and continue to fill the form.
So, here's what you should do.
<!-- Put this hidden input inside of your form tag -->
<input name="_recaptcha" type="hidden">
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITEKEY_HERE"></script>
<script>
// This will generate reCaptcha token and set to input hidden
const generateRecaptcha = function() {
grecaptcha.execute(
"YOUR_SITEKEY_HERE", {
action: "YOUR_ACTION_NAME"
}).then(function(token) {
if (token) {
document.querySelector("input[name='_recaptcha']").value = token;
}
});
}
// Call it when page successfully loaded
grecaptcha.ready(function() {
generateRecaptcha();
});
// Do your AJAX code here
$.ajax({
url: "https://example.com",
success: function(response) {
console.log(response);
},
error: function(error) {
// Call again the generator token reCaptcha whenever error occured
generateRecaptcha();
}
</script>
Don't forget to put your Site key and your action name. Make sure the action name matches with your Backend action name.
Medium Article
I need to create a condition to show confirmation message to validate if a session is existing in the site before logging in.
If user is currently logged in the site with the same username / credential or if session is existing then it will call the confirmation message and execute the action after clicking OK.
How do I create the condition before calling the confirmation message?
function checkSession()
{
//call SQL
varSQL = "Select * from user_table where user = 'user'";
objCmd.ActiveConnection = objCon;
objCmd.CommandText = varSQL;
objCmd.CommandType = 1;
objRec = objCmd.Execute();
var user = objRec("user");
if (if user is not null)
{
return confirm("Please click OK to terminate the session and proceed to login.");
}
}
<input type="submit" value="Login" onclick="return checkSession()"/>
It doesn't work if I try to add another condition on the confirmation function which is checking from database
I have the following scenario. Actual Page loading starts, user login is checked for authentication. If access granted, actual page loading completes and user can access the page. If access denied, actual page loading stops and user is redirected to 'access denied' page.
Infact the scenario should be like this. User authentication is checked. if access granted, actual page loading starts and user can access page. If access denied, user is directly directed to 'access denied' page.
can someone tell me how to include promise for this scenario. current code is as follows.
$q.when().then(function () {
return $rootScope.$emit('resetView', false, 'default');
}).then(function (result) {
loadNavBar(); //actual page loading starts here
}, function (error) {
$log.error("Caught an error:", error);
return $q.reject('New error');
});
the below function is loadNavBar() which gets executed. User authentication is done inside of this. Hence page loading starts and then user is checked. I want user to be checked first itself and then load page accordingly depending on his access rights.
var loadNavBar = function () {
//few functions here to display page.
//below code to check user authentication
var serviceURL_CheckUserExists = '/api/Pre/CheckUserExists';
//ajax to check if user exists in database. give/ deny access based on user present in DB and if user is set as blockuser in db.
$.ajax({
type: "GET",
url: serviceURL_CheckUserExists,
}).then(function (response) {
if (response.Results.length == 1 && response.Results[0].BlockUser == false) { //user has access if condition is satisfied.
$rootScope.myLayout.eventHub.emit('getUserName', response.Results[0].User_ID.trim());
$scope.role = "";
var details = response.Results[0];
for (var parameters in details) {
if (details[parameters] == true) {
$scope.role += parameters + ',';
}
}
$scope.role = $scope.role.replace(/.$/, ".");
var firstname = response.Results[0].FirstName;
firstname = firstname.replace(/\s/g, '');
$scope.$apply(function () {
$scope.username = response.Results[0].FirstName + " " + response.Results[0].LastName;
});
}
else { $window.location.href = '../../../BlockUser.html'; } //block access to actual page and redirect to 'access denied' page.
}
}
});
};
i think that the right approach to your problem is to use resolve property in the route, so the user can't navigate to certain pages if he isn't logged in and once he logged in you can inject the user object to the controller
for example to navigate to home page you must be logged in
.when("/home", {
templateUrl: "homeView.html",
controller: "homeController",
resolve: {
user: function(AuthenticationService){
return AuthenticationService.getUser();
}
}
})
app.controller("homeController", function ($scope, user) {
$scope.user = user;
});
https://www.sitepoint.com/implementing-authentication-angular-applications/
Here's a quick example of hiding the content until the user is authenticated to see it. Click the 'authenticate' button to trigger the function that you would run if the user is authenticated by your ajax call. Showing the content can be done with a fuction like:
function userIsAuthenticated(){
document.getElementById('pageContent').style.display = 'block';
}
See JsFiddle for a simple implementation.
I have a php code for logout page but i need to have a confirmation box pop-up first if i click the navigation box to logout...if I want to logout or not...can any1 help me?? please
code:
<?php
include("connection.php");
// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();
$uid = $_POST['uid'];
$stat="UPDATE users SET status='logout'";
mysql_query($stat);
// Jump to login page
header('Location: index.php');
?>
maybe this is what you are trying to achieve?
var logout = confirm("Are you sure to logout?");
if(logout){
location.href = "pathtologout.php";
}
Most simple:
Logout
If you just need a simple confirmation, you can do this
$('#logout').click(function(){
var reallyLogout=confirm("Do you really want to log out?");
if(reallyLogout){
location.href="path/to/logout/file.php";
}
});
If you can't use jQuery(!), you can use pure Javascript to attach the event handler
function logout(){
var reallyLogout=confirm("Do you really want to log out?");
if(reallyLogout){
location.href="path/to/logout/file.php";
}
}
var el = document.getElementById("logout");
if (el.addEventListener) {
el.addEventListener("click", logoutfunction, false);
} else {
el.attachEvent('onclick', logoutfunction);
}