I'am trying to delete an entry/offer from the database and then get back to all the entries/offer overview page. I tried to do it with Javascript but unfortunately it does not open the overview page. It does the deleting but then stays on the page.
Is that the correct way anyways with javascript?
Here the two links Overview and delete Offer
<a id="overview" href="/mbm-kalkulation">Overview</a>
<form method="post" action="/?id='.$_REQUEST["id"].'" name="delOffer"><button type="submit">delete Offer</button>
Here the javascript which should click the overview page after the form got submitted.
((isset($_REQUEST["delOffer"]))?'
setTimeout(function(){
jQuery("a#overview").click();
}, 1000);
':'')
Normally such redirects are done using the header function from php. This is only possible, when the headers weren't already send. In this case you will have to use a JavaScript fallback. The code could look something like this:
if (isset($_REQUEST["delOffer"])) {
if (!headers_sent()) {
header("Content-Type: text/plain");
header("Location: {$url}");
} else {
print "<script>window.location = '" . addslashes($url) . "';</script>";
}
exit;
}
Why my code still loop submit form ?
When load page delay 1 sec and then submit form by javascript in the same time clearInterval so i want to know why my code still loop submit form ?
<?PHP
session_start();
include("connect.php");
?>
<form class="form" id="fid" method="post" action="" ENCTYPE = "multipart/form-data">
<input type="text" id="support" name="support" value="555">
</form>
<script>
var timer_var = null;
timer_var = window.setInterval(function (){
document.getElementById("fid").submit();
window.clearInterval(timer_var);
}, 1000);
</script>
<?PHP
if(isset($_POST["support"]))
{
?>
<script>
alert("test");
</script>
<?PHP
}
?>
Personally I would use setTimeout if it's a task that should be executed just once.
Let me explain you the problem. When the page loads you try to execute some code. Within this code you are submitting a form which will reload the page. This happens to cause the infinite loop.
If you want to submit data without reloading the page you could make an ajax request where you send the data that was entered in the input fields
Here you can find a very clear explanation:
Submit form without reloading page
When I try to run this script:
<form class="form-inline" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<button type="submit" name="buttonSubmit" class="btn btn-default">Submit</button>
</form>
<?php
if (isset($_POST['buttonSubmit'])) {
unset($_POST['buttonSubmit']);
echo "<script>alert(".isset($_POST['buttonSubmit']).")</script>";
echo "<script>location.reload(true);</script>";
}
?>
As a result, the page is refreshing in an infinite loop.
What is the reason?
How do I refresh my website only once?
When you use location.reload(true);, you do the same, programmatically, as clicking on the browsers "Refresh/Reload" button.
This will generate yet another "submit", over and over, hence always make the statement isset($_POST['buttonSubmit']) be true.
Here are a couple solutions:
location.href = 'page-to-load';
location.assign('page-to-load');
location.replace('page-to-load');
The Location.replace() method replaces the current resource, and after that the current page will not be saved in
session History, meaning the user won't be able to use the back button either,
to navigate to it and cause a repeated "submit", which normally will occur.
Note, if the 'page-to-load' is the same being already loaded, you can use location.href, e.g.
location.replace(location.href);
Yet another way would be, instead of rely on a client side script, to do a response redirect upon a form submittion, server side.
How to make a redirect in PHP?
This helped me:
Change location.reload(true); to window.location.href = '';
I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}
Hi I have an inquiry form with 3 steps
Step 1: small inquiry form (which is currently passing form fields to the step 2 page)
Step 2: full page inquiry form (this form submits and processes data via form processing script - form-process.php which then redirects user to thank you page and sends email to site admin)
Step 3: Thank you page (this page is in Joomla while the above two pages are standalone PHP pages accessed via FTP. )
I'd like to print the form fields (from the form in step 2) to the thank you page.
I am currently using php session to transfer field values from step 1 to step 2 which is working fine, however the same code doesn't bring form value from step 2 to thank you page.
My code is
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
I also use in every single page.
<?php
if(isset($_SESSION['error_msgs'])){
$_SESSION['error_msgs'] = '';
unset($_SESSION['error_msgs']);
}
if(isset($_SESSION['sucess'])){
$_SESSION['sucess'] = '';
unset($_SESSION['sucess']);
}
if(isset($_SESSION['form1data'])){
$_SESSION['form1data'] = '';
unset($_SESSION['form1data']);
}
?>
Can someone help why i am not able to pass values from step 2 to thank you page? I have also put the session() code into the form processing script which fires after step 2 submit button.
i have just added the below code into thank you page and it says below message.
Notice: A session had already been started - ignoring session_start() in /tmp/html1jVKJt on line 5
No data
the code i have placed on confirmation page.
<?php
if(isset($_SESSION['error_msgs'])){
$_SESSION['error_msgs'] = '';
unset($_SESSION['error_msgs']);
}
if(isset($_SESSION['sucess'])){
$_SESSION['sucess'] = '';
unset($_SESSION['sucess']);
}
if(isset($_SESSION['form1data'])){
$_SESSION['form1data'] = '';
unset($_SESSION['form1data']);
}
?>
but form field (first name) is still not printing on the confirmation page.
So it seems like the session is passing from step 1 to step 2 to step 3 (confirmation page) however is not printing the input field.
I am using into confirmation page to show submitted email.
<input type="text" value="<?php echo $_SESSION['user_email']; ?>"/>
Any feedback will be appreciated. thanks