How to Refresh a .php Page After Form Submitted? - javascript

This seems to be pretty basic but I've looked at all the suggestions (online) I can find -- and they did not work -- so I thought I might as well ask the Stack-Community.
I simply want my page to refresh AFTER the form is submitted.
I have my php Session Header first on the .php page:
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($userinfo[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
}else {
echo "Wrong username or password.";
}
}
I then have a form start code:
<form action="" method="post" >
I have used different inside the action " " but these don't seem to work.
I also then have a input type " " that looks like this:
<input type="submit" name="submit_invoice" value="Submit" />
However, nothing I alter in this makes the page load AFTER the form is submitted.
Here are some of the things I've tried on either the FORM or the INPUT TYPE areas OR after the query to update the mysql record in the DB. Please Note: I am able to update the data in the DB so the code is working . . . but nothing seems to work. I must be doing a little thing wrong.
header('Location: ' . $_SERVER['PHP_SELF']);
location.reload();
When I use header() the error is that the header is already set up so can't do it again. Location reload simply does not reload.
Any help, much appreciated.

Try this:
header('Location: ' . $_SERVER['PHP_SELF']);
die('<META http-equiv="refresh" content="0;URL=' . $_SERVER['PHP_SELF'] . '">');

Related

Submit form and then after the form is processed open a new page

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;
}

I need the answer from a form to immediately redirect to another form

I have a one question radio button form. I want the answer to immediately redirect to page A if the answer is A or redirect to page B if the answer is B. I know that the answer probably relies on javascript, but I am fairly new to coding and javascript is my Achilles' heel.
I have the form selecting and a basic if else statement - just not sure how to tie the two together. Some other questions here were helpful, just not enough to fully help me put something together. Here is my current code:
<?php
echo '<form id="gate" action="index.php" method="post">';
echo '<p>question<br>';
echo '<input type="radio" name="gateway" value="A">answer A<br>';
echo '<input type="radio" name="gateway" value="No">answer B<br>';
echo '</p>';
// branching for different forms
if($gateway=="Yes") {
header ('answer Yes url');
} else if($gateway=="No") {
header ('answer No url');
}
echo '</form>';
?>
</body>
</html>
I currently click on Yes or No and nothing happens. I would love some help connecting A and B to my statement. I would love to be able to do it without the user having to click Submit - have it redirect when they make the choice.
First you should check if request is a POST, then fetch your 'gateway' from the post.
Note that after a redirect in php you have to stop the script with a die() or with exit().
Below is an example
if (isset($_POST)) {
if ($_POST['gateway'] == "Yes") {
header("Location: <YOUR YES URL>");
die();
} else {
header("Location: <YOUR NO URL>");
die();
}
}
To achieve the form submit on checking the radio input, your best option would be to put onclick="this.form.submit();" on your radio inputs
you may try:
echo '<input type="radio" name="gateway" value="A" onchange="this.form.submit()">answer A<br>';
as suggested in Submit form on radio button click

How to prevent data submission after refresh [duplicate]

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";
}

display a div/span only after $_SERVER['HTTP_REFERER'] has been executed

I tried to approach it numerous ways, but somehow I'm not able to figure it out. Maybe you guys can help me?
I need to display a certain div/span or whatever container to display a text after page goes back via
header('Location: ' . $_SERVER['HTTP_REFERER']);
The reason why I need such a wierd approach to display something is that I'm using a href/GET combination to run a PHP function when my link gets klicked. (submit button is in use by another function/module so I can't use that )
HTML part
<p id="show_project">
<a id="add_to_project" name="add_to_project" href="?function">
Add to project
</a>
</p>
PHP function part
$this->getProductinfo();
if (isset($_GET['function'])){
$this->getSQLQuery($_GET['function']);
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
Any ideas ?
BR's
Why not add a message to your header() call
$this->getProductinfo();
if (isset($_GET['function'])){
$this->getSQLQuery($_GET['function']);
header('Location: ' . $_SERVER['HTTP_REFERER'].'?msg=We got a message');
}
Get the message
<?php
session_start();
if (!empty($_GET['msg'])){
$_SESSION['msg'] = $_GET['msg'];
header('Location: ' . $_SERVER['HTTP_REFERER']);
die;
}
else{
if (!empty($_SESSION['msg'])){
$msg = $_SESSION['msg'];
unset($_SESSION['msg']);
}
}
?>
<?php
/* Later in the document */
echo '<div>' . $msg . '</div>';
?>
You will need to sanitise and validate the $_GET variable
borrowed from here

href call in javascript

I have a problem with using , during
click of the link, I need to update a field in the database and redirect to another page after.
I have this code:
<a href="#" onclick="<?php
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."'
WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
$logger->debug('OK');
}
else
{
$logger->debug( 'NOt OK');
}
?>"> </a>
After the php end tag '?>' can I add my path to be directed to? like:
<a href="#" onclick="<?php
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."'
WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
$logger->debug('OK');
}
else
{
$logger->debug( 'NOt OK');
}
?> ../index.php"></a>
Is that even possible?
What is the right thing to do it?
Thanks a lot!
this is not the right way.
There can be multiple ways you could take to do this. But I'd suggest you to place the DB update code in the target page (that I assume you mentioned as index.php). If you only want to trigger the DB update code on clicking of the link, use a page in middle to redirect the flow.
So, your page flow will be:
Current Page (Link Clicked, simple href to middleman.php) ==> middleman.php (just run the DB update code here and use header Location syntax to index.php) ==> index.php
codes:
page in which you have the link
source.php
<.... html contents ....>
<a href='middleman.php'>Visit the page</a>
<.... more html contents ....>
middleman.php
<?php  
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."' WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
 $logger->debug('OK');
}
else
{
 $logger->debug( 'NOt OK');
}
header("Location: index.php"); //redirects to index.php
?>
index.php
do whatever you want
When a page is rendered, php code will run once. Whenever you see a webpage, it's only html, always, with no live access to the php code. So, you cannot execute php blocks directly from for example a javascript event. In your case the sql query would execute once, when you load the page.
kishu27 just posted one of the proper ways to do it, and the best option for you in this case. If you only wanted to update the database, without being redirected to another page, an ajax call to a php page with the database code would be a good alternative.
Using location.pathname

Categories

Resources