Self submitting form, then refresh page? - javascript

I have a page in PHP with a form that contains multiple checkmarks. These checkmarks can be used to either DELETE the records or create LABELS for whatever is selected.
I got the delete section going just fine as I use the same page ($_SERVER['PHP_SELF']) to run a query, but the labels isn't working because I need to pass the values to another page called PDF_Label_Print.php. I would like to stay away from session variables if possible.
The page works, but sometimes it doesn't refresh automatically. Any ideas? Thanks!
if (isset($_GET['labels']) && (is_array($news_ids) && count($news_ids) > 0))
{
$label_list = implode(',', $news_ids);
echo "<form action='PDF_Label_Print.php' method='post' name='frm' target='_blank'>
<input type='hidden' name='full_list' value='". htmlentities(serialize($label_list)) ."' />
<input type='hidden' name='tbl_name' value='" . $_SESSION['officeid'] ."' />
<input type='hidden' name='report' value='list' />
<input type='hidden' name='avery' value='5160' />
</form>";
echo "<script language='JavaScript'>document.frm.submit();</script>";
// refresh page.
echo '<script language="javascript">window.location = "welcome.php"</script>';
}

the problem is that after submitting a form javascript might stop working till the post is done, and the form action is another page.BUT again, when submitting a form (without ajax) the page should refresh automatically.
So what you need is on the PDF_Label_Print.php page to redirect back to the welcome page
header("location:welcome.php"); // or anyother page you want to redirect after posting

Thank you for everyone who took to their time to look at my question.
Turns out I was able to resolve the issue by using POST instead of GET on my form. The header location is now refreshing the page correctly.

Related

How to make an input value permanent in wordpress or work with global variables

I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>

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

HTML form POST to direct print page

I have the page VIEW-SALE.PHP
on this page I have a submit button form to view the invoice in print format, there is the code:
<span style='display:inline-block'>
<form name='print' id='print' action='print-invoice.php'
target='_blank' method='post'>
<input type='hidden' name='invoice' value='$invoice'>
<input class='submit-all' type='submit'
value='Print the invoice'
onClick='window.print();return false'></form></span>
The code must just open the page PRINT-INVOICE.PHP and print it but when I click it it show the print dialog but of the current page I am VIEW-SALE.PHP so it does not show the PRINT-INVOICE.PHP
How does it can be done?
doesn't post just post data you may need a header redirect the redirect being php code
header("Location: blabla")
I found this you may find it of help
redirect after submit
the problem is the onClick='window.print();return false'. The window object is the current window containing the form. You should include an javascript event handler in your PRINT-INVOICE.PHP:
... <body onload="window.print()"> ...

Passing to another page using form and window.open. The other page is not receiving the value

This is my initial page code
$_POST["i"] is the url that I have sent from the previous page and it works fine here. This is also the value that I am trying to send to the next page through the hidden field.
<form name="f1" method="post" action="window.open(/mydir/product-cat/brookbond?add-to-cart=89" rel="nofollow" data-product_id="89" data-product_sku="" class="add_to_cart_button button product_type_simple)">
<input type="hidden" name="k" value="<?php echo $_POST["i"]; ?>" >
<img src="<?php echo $_POST["i"]; ?>" />
<input type='submit'>
</form>
Receiving end code in the next page
<?php echo $_POST["k"]; ?>
It is not receiving any value and thus not printing anything.
Everything else works as expected.
Any help would be greatly appreciated.
NOTE: I cannot substitute the window.open function, it serves a definite purpose.
Not the most elegant of solutions, but maybe you can add it to the url of the window.open.
... window.open(/mydir/product-cat/brookbond?add-to-cart=89
& k="<?php echo rawurlencode($_POST["i"]);?>"
You can't send it the way you do. If you don't want to reload page and send post data then you need to use AJAX.
On this page you will find examples how to do it. You need to bind submit() event for form and then send ajax request to the page you want and process the results.
The other option is to use GET instead of POST but this window.open doesn't look good anyway.

javascript lightbox causes error when updating mysql table

I have created a comment-reply system for my blog in php. Comments are stored in a table called comments(comments_id, comment, comment_date, user, flag). I use a script which displays comments and near to each comment there is a link called "delete" in order for the user to delete its own comment in case want to do so.
my php script for displaying comments is :
<?php
// ... above code
$comments .= $row['comment']; // comment printed succesfully here
if($comment_user_id == $session_user_id){
$comments .="<table border='1' style='display:inline-table;'><td><h2><font size='2'>
<form action='deletepost.php' method='post'>
<input type='hidden' name='var' value='$comment_id;'>
<input type='submit' value='delete'>
</form>
</h2></font></td></table>";
}
?>
in order to delete a comment, I update the table comments and set flag=1, so my script will not display comments having their flag=1 in table. In order to do this I use script deletepost.php
<?php
$comment = mysql_real_escape_string($_POST['var']);
if(isset($comment) && !empty($comment)){
mysql_query("UPDATE `comments` SET `flag`=1 WHERE (`user`='$session_user_id' AND `comments_id`='$comment')");
header('Location: wall.php');
}
?>
My script until now works perfect without problem and the user that posts a comment can delete its own comment without any error. The problem started when I decided to insert a lightbox in javascript, so that the user will be asked before deleting a comment. So I have changed my first script to the following:
<?php
// ... above code
$comments .= $row['comment']; // comment printed succesfully here
if($comment_user_id == $session_user_id){
$comments .="<table border='1' style='display:inline-table;'><td><h2><font size='2'>
// at this point problem occurs when inserting javascript lightbox
<a href = javascript:void(0) onclick = document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'><h2><font color=green size=3>Delete All</font></h2></a>
<div id=light class=white_content>DELETE THIS COMMENT?
<form action='deletepost.php' method='post'>
<input type='hidden' name='var' value='$comment_id;'>
<input type='submit' value='delete'>
</form>
<a href = javascript:void(0) onclick = document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'><div id=pading><button>Cancel</button></div></a></div>
<div id=fade class=black_overlay></div>
</h2></font></td></table>";
}
?>
By using the javascript lightbox as shown above, when the user will press delete, a lightbox starts and asks user if wants to delete the comment. The problem is that now when the user press delete button, it is not deleting the certain comment but the last comment that finds in comments table. Probably there is something else I need to write in my javascript to correct this, in order to know which comment to delete (set its flag to 1). Any idea how to fix it?
Make sure the 'deletepost.php' is getting the correct comment id($comment) that you wanted to delete.
May be that can be the cause.

Categories

Resources