How to prevent a php page from browser back button? - javascript

I have a form which contains many drop-down and numeric slide-bar.
I am using post method to pass the selected variables to another page. Where I am getting the variables in the next page by $_POST() method.
And I am updating the variables passed into the database, after updation giving javascript pop-up as "you have saved successfully".
So my problem is when I click on browser back button, the values are getting updated in the database again and again. How can I prevent this by disabling browser back button.

You can have your post method open up a new tab so that there is no back navigation to go to:
<!DOCTYPE HTML>
<html>
<body>
<form action="www.google.com" method="post" target="_blank">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#theSubmit').on('click', function () {
setTimeout(function(){
window.close();
}, 500);
})
</script>
The target generates the new window
And if you would like to close the old window add the two scripts that close the previous tab 500ms after the new tab is opened.

Instead of disabling the back button, you could redirect the user if he gets back to the page using sessions.
page1.php
session_start();
if (isset($_SESSION['block'])) {
header('Location: page2.php');
}
page2.php
session_start();
$_SESSION['block'] = true;
Another option:
This is how you could set values of all your input fields back, if the user clicks back:
page1.html
var block = localStorage.getItem("block");
window.addEventListener("beforeunload", function() {
if (block === 1) {
const block = true;
}
});
if (block) {
const inputs = document.getElementsByTagName('input');
for (input of inputs) {
input.value = '';
}
}
page2.html
localStorage.setItem("block", 1);
In this case, if you don't want your values get updated in your database, use:
if (!empty($_POST['my_value']) { // Add to database })

Don't disable the back button, fix the problem that the data is saved multiple times instead. You could use pass the users to a separate page with message "you have successfully...".
Then if the user tries to go back you look at $_SERVER['HTTP_REFERER'] if that is "successful.php" then don't save the data.
Disabling back buttons is a big reason for me to block a page so that I can't visit it again.
I truly hate when they do that or add several pages that you have to click back to get out of a page.

Whenever you post your data then you should check your post data that this is empty or not
<?php
if(isset($_POST) && !empty($_POST) ){
//your code for update
//Then after run update query and success message ,do empty the post
$_POST=array(); // empty the post
}
?>

Related

Submit form one time after page load via Jquery

How to submit the cart request-quote form after page load?
Below code is worked fine -
<?php if(!isset($_GET['updated'])) { ?>
<script>
jQuery(document).ready(function($) {
jQuery("#yith-ywraq-form").submit();
});
</script>
<?php } ?>
But avoid submitting forms, again and again, I reload to this action
site.com/request-quote/?updated=data
But if someone refreshes the same page site.com/request-quote/?updated=data
then I have no option to submit the form again on page load.
do you have a solution for this problem?
My requirement is I want to submit the cart request-quote form 1 time after page load?
You may use localStorage for this.
Take a flag in set some initial value of it.
When the form submits update it's value.
By checking the same you can avoid getting submit.
<?php if(!isset($_GET['updated'])) { ?>
<script>
if(!localStorage.getItem('isFormAlreadySubmit')){
jQuery(document).ready(function($) {
jQuery("#yith-ywraq-form").submit();
localStorage.setItem('isFormAlreadySubmit', true);
});
}
</script>
<?php } ?>
You can move $_GET['updated'] to localStorage or sessionStorage, then you don't need to reload the page to ?updated=data page anymore.
localStorage will save updated value even when the browser is closed and reopened.
sessionStorage will save updated value but it will be cleared if the browser is closed.
That depends on you to choose which one. So I make a demo with sessionStorage which I prefer because when the user closes the browser, it will clear the updated value, maybe the next user in that device is another (public device). I also remove the check if(!isset($_GET['updated'])) condition.
<script>
jQuery(document).ready(function($) {
if (!sessionStorage.getItem('updated')) {
jQuery("#yith-ywraq-form").submit();
sessionStorage.setItem('updated', true);
}
});
</script>
Update: add live demo https://codepen.io/tuandaodev/pen/jOwvrRg?editors=1111
You need to use a server side session variable to check (duplicate)
Answer

refresh div (populated by jquery) when form (inside div) is submitted

Here is my scenario. I have a 'Master Page (Course_Maintenance.php)' that has 2 divs on it. The first is populated from the code on Course_Maintenace.php. The second div populates using the following:
$(document).ready(function() {
$("select[id='SelectCourse']").change(function() {
var link = 'CourseTeeInfo.php?CourseID='+$(this).val();
$('#CourseTeeInfo').load(link);
})
});
The CourseTeeInfo.php page has a form that populates and works perfectly. I use a staging system on that page:
// Get stage of form
if(!isset($_POST['btn_submit']) || !$_POST['btn_submit']) { $stage=0; }
if(isset($_POST['btn_submit']) && $_POST['btn_submit'] == 'submit') { $stage=1; }
So once the form is filled out and validated, I use javascript to change the value of btn_submit to come back to the form to use PHP to write to the MySQL database:
function ValidateForm() {
if(!noErrors2()) { alert("You must fix errors on page before submitting"); }
document.getElementById('btn_submit').value = "submit";
document.TeeInfo.submit();
}
Currently I have Stage 2 just echoing the $_POST variable to the screen. This all works if I call CourseTeeInfo.php directly. However, when I click the Update button on the form (which fires the ValidateForm() javascript) within the div on Course_Maintenace - the div refreshes to a blank screen rather than the $_POST variable display (as it does running directly).
Any insight on how to have the div refresh properly in the parent (Course_Maintenace.php) window would be greatly appreciated. I simply want the div to work exactly like the form works if called directly. My goal is that after I successfully write the record (in $stage=1) that I will reload the form (yet again) back to $stage=0 which will then have the new/updated information.
Thanks in advance for the help.
I changed the approach slightly and used jQuery AJAX calls to write to the MySQL database (instead of reloading the form). After writing the record, I simply refreshed the div using the jQuery .load function.

Greasemonkey doesn't execute again after form prints result

I'm using greasemonkey to manipulate a form on an existing web page. (autofill)
The action attribute of the form is itself, once submitted it prints a success message above the submit button.
What I'm trying to do is, once the form is submitted - I want to redirect the browser to another page. But this doesnt work with greasemonkey. Nothing happens.
I wrote a code to detect when the page is submitted, but doesnt work after the form is submitted.
getData("goingback"); //pulls the goingback data from database using ajax
if (goingback == "yes") {
window.location = "index.php";
} else {
//business as usual
// manipulate the form and get it ready for submission
sendPost("goback","yes"); // this function sends data to a php to be handled via ajax
//ajax stores the data in database
//the form is submitted using a timer and .click();
var submission = Math.floor(Math.random() * 10000) + 5000;
setTimeout(function() {
$('button[value="submit"]:first').click();
}, submission);
}
How can I achieve this?
Thanks in advance
The question is not clear; we might need to see the actual page itself. But, it sounds like the page is submitting the form via AJAX, and not a full post.
In that case, your script won't refire. Instead, monitor the page for the success message. Here's one way:
Suppose the success message is like this:
<div id="post_status">
<h2>Some one set us up the (data) bomb!</h2>
</div>
where the <h2> is added after the form posts.
Then this code will redirect after the post happens:
var postChkTimer = setInterval (checkForPostDoneNode, 200);
function checkForPostDoneNode () {
var postDoneNode = $("#post_status h2");
if (postDoneNode.length) {
window.location.assign ("index.php");
}
}
There is no need for that getData("goingback") or
sendPost("goback","yes"). Also that looks like it's setting goback but checking goingback -- which could be a problem. Although it is not the problem causing the behavior as described in the question.

PHP and window.close in JavaScript

I have a problem. I have a page that when you click a button, a popup with a form is shown. So, I complete some data and I submit. What I want to do is, to submit the form, close the form and refresh the parent page. I don't want to do it with AJAX.
The problem is that in my parent page I have to refresh content with the input information of the form.
So when I refresh, sometimes the data is shown and sometimes not. Do you know why this could happen?
I just use onsubmit="refreshParent()" in my form. The info is stored always in my database, so I think the problem may be that sometimes the refresh catches the new info and sometimes not.
function refreshParent() {
window.opener.location.reload();
window.close();
}
I use this to reload the page that opened a popup window:
<script language="JavaScript">
<!--
function reloadParentPage() {
window.opener.location.href = window.opener.location.href;
if (window.opener.progressWindow) {
window.opener.progressWindow.close()
}
window.close();
}
//-->
</script>
By the way, the code above is called by a link or button in the popup page.
You have a race condition between the script doing the insert and the script reloading the parent.
The solution is to call refreshParent on the page after the submit - that way you know the data is in the database. You don't even have to do it on document ready - return a stub page that just defines and calls refreshParent in the head tag.
In PHP when you run post script, at the end, include this code :
echo '<html><script language="javascript">
parent.location.href="http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"].'"; // or any other url
</script></html>';
This will output a javascript that will reload the windows.

Disable "Back" & "Refresh" Button in Browser [duplicate]

I am doing web development.
I have a page to do with credit card, which when user click "refresh" or "Back", the transaction will be performed one more time, which is unwanted.
This include Browser top left "Back" & "Refresh" button, "right click->Refresh/Back", press "F5" key.
This is to be done on certain cgi page only, not all of them.
Can this be done using Javascript? Or any other method?
The standard way is to do it in 3 steps.
the form page submits fields to processing page
processing page processes data and redirects to result page
result page just displays results, reloading it won't do any harm.
This breaks the basic browser user experience model...users should always be able to use the Refresh and Back buttons in their browser. Recommend that you fix your page another way.
If you update your question to include the server language/platform/technology that you are using then someone might be able to suggest a solution.
The simple fact that resubmitting the form generates a duplicate transaction is worrying. You should have some sort of check to ensure each submit of form data is unique.
For example, the page which would submit the form should be given a unique ID that gets submitted with the form. The business logic should then be able to recognise that the form submitted has already been processed (as the (no longer) unique ID will be the same), so ignores the second attempt.
The 'standard way' still doesn't stop clients from clicking the back button twice... or even going back and resubmitting the form if they don't think (for whatever reason) it has been processed.
generate a random string and store it in session,
then output it to your form as a hidden value,
check the submitted and store variable, if matches process your request,
go to 1.
Place this code on the form page
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now-new TimeSpan(1,0,0));
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetAllowResponseInBrowserHistory(false);
You shouldn't try to "block" these actions.
What you should do is make sure that nothing happends when someone "double submits" the form.
and in some browser you canĀ“t even do that, and this is good!
The best way is to have enough session handling logic that you can recognise the 2nd (and onwards) attempt as "this is just a re-submission" and ignore it.
I didn't see this here so here it is.
Put a unique token in the form.
The submit button triggers an xmlhttp(ajax) request to the server to create a session variable named after the token with a stored value of 1.
The ajax request submits the form after receiving a positive state change.
The form processing script checks for the session variable withe the stored value of 1.
The script removes the session variable and processes the form.
If the session variable is not found, the form will not be processed. Since the variable is removed as soon as its found, the form can only be run by pressing the submit button. Refresh and back will not submit the form. This will work without the use of a redirect.
vartec:s solution solves the reload-problem, not the back-problem, so here are a solution to that:
The form page sets a session variable, for example session("fromformpage")=1
The processing page check the session variable, if its ="1" then process data and redirect to result page if any other than ="1" then just redirect to result page.
The result page sets the session variable to "".
Then if the user is pressing back button, the processing page will not do the process again, only redirect to process page.
I found the above Post/Redirect/Get explanations a little ambiguous
Here's what I followed and hopefully it helps someone in the future
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
Essentially the process based on the above solution is:
Submit from the FORM page to the processing page (or to itself)
Handle database or payment processing etc
If required, store user feedback message in a session variable, possible error messages etc
Perform header redirect to results page (or to original form page). If required, display custom message from processing page. Such as "Error Credit Card payment was rejected", and reset session variables.
Redirect with something like:
header("HTTP/1.1 303 See Other");
header("Location: http://$_SERVER[HTTP_HOST]/yourfilehere.php");
die();
The header redirect will initiate a GET request on "yourfilehere.php", because a redirect is simply that, a "request" to fetch data FROM the server, NOT a POST which submits data TO the server. Thus, the redirect/GET prevents any further DB/payments processing occurring after a refresh. The 301 error status will help with back button pressing.
Helpful Reading:
http://en.wikipedia.org/wiki/URL_redirection#HTTP_status_codes_3xx
http://www.theserverside.com/news/1365146/Redirect-After-Post
http://wordsideasandthings.blogspot.ca/2013/04/post-redirect-get-pattern-in-php.html
https://en.wikipedia.org/wiki/HTTP#Request_methods
http://en.wikipedia.org/wiki/Post/Redirect/Get
Just put this javascript on the html section of aspx page above head section
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
We need to put it on the html section of the page which we want to prevent user to visit by hitting the back button
Complete code of the page looks like this
<%# 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>Untitled Page</title>
<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</head>
<body onload="disableBackButton()">
<form id="form1" runat="server">
<div>
This is First page <br />
<br />
Go to Second page
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/Default2.aspx">Go to Second Page
</asp:LinkButton></div>
</form>
</body>
</html>
If you are using firefox then use instead of onload
If you want to disable back button using code behind of aspx page,than you need to write below mentioned code
C# code behind
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "<script language="javascript">\n";
strDisAbleBackButton += "window.history.forward(1);\n";
strDisAbleBackButton += "\n</script>";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
We can also achieve this by disabling browser caching or cache by writing this line of code either in Page_load event or in Page_Init event
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Doing this,user will get the page has expired message when hitting back button of browser
Demo is :
This code works for not back from current page me..
Here I put a code which helps you , not open contextmenu and on browser reload ask you leave a page or not...
I am trying the ask click on browser back button
jQuery( document ).ready(function() {
document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;
var wasPressed = false;
function fkey(e){
e = e || window.event;
//alert(e.keyCode);
if( wasPressed ) return;
if (e.keyCode == 116 || e.keyCode == 8 || e.keyCode == 17) {
// alert("f5 pressed");
window.onbeforeunload = null;
return true;
}
}
window.onbeforeunload = function (event) {
var message = ''; // Type message here
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
jQuery(function () {
jQuery("a").click(function () {
window.onbeforeunload = null;
});
jQuery(".btn").click(function () {
window.onbeforeunload = null;
});
//Disable part of page
$(document).on("contextmenu",function(e){
return false;
});
});});
Thanks,

Categories