Keeping form values after POST - javascript

I have a form, which on submitted goes to a php file and inserts values into DB(MySql).After successfully inserting values into DB, I want to return back to form screen, with values previously entered and posted.
Actually I am using the below code to return back to form page, but am unable to load fields with previous values.
echo "<meta http-equiv='refresh' content='1; URL=form.php'>";
form.php file contains form and add_form.php adds values to database. The above code is written in add_form.php on sql query success
Suggest me an easier way of doing this

This is how I do it when I need to retain data that is posted via PHP form
if (isset($_POST['your_button_name'])) {
foreach ($_POST as $field => $value)
$this->settings[$field] = $value;
}
and if I need to refer, I simply do $this->settings['field_name']
note: you will ofcourse have to define variable $settings and make sure to sanitize the data

In your add_form.php after saving data you can redirect like this.
$url = 'form.php?'.http_build_query($_POST);
header('Refresh:5; url= $url');
And in your form.php you can do this.
<input type="text" name="something" value="<?php echo $_GET['something']; ?>" />

you can try JavaScript ajax to do this~

Related

How to change a HTML table data value after form submission

I have a form.
<form action="form.php" method="POST" name="form1" id="f1">
On this form is an input for a name.
<input type="text" class="form-control" id="n1" placeholder="Name" required>
The user inputs their name and clicks submit, the form.php then kicks in and this name is emailed to an email address.
$name = $_POST['n1'];
If this is successful the user is redirected to another page via;
header("Location: /anotherpage.html");
Up to this point everything works fine.
On this page is a HTML table with a table data cell;
<td id="table1"></td>
Q. What I am trying to do is when the user is redirected to this page the name they submit appears in the tables data cell.
I have tried a couple of things with no success.
On the HTML side;
value="<?php echo $name;?>" & value="<?php echo $_POST['n1'];?>" within the td tag.
<?php echo $name;?> & <?php echo $_POST['n1'];?> between the td tags.
& on the PHP side after the redirect header;
getElementById('n1').value = $name;
getElementById('n1').value = $_POST['n1'];
Is there a way of doing this?
Look forward to hearing from anyone
Kind Regards
You can send the name over the url using the header using PHP...
// check the submission of your form using the name set in the submit button...
if(isset($_POST['submit'])){
// DO NOT SKIP ON SANITIZING YOUR INPUTS!!!!!
// This example is very basic, I am not showing how to sanitize inputs
$fname = filter_var(strip_tags($_POST['fname'], FILTER_SANITIZE_STRING));
$lname = filter_var(strip_tags($_POST['lname'], FILTER_SANITIZE_STRING));
// do your email stuff
// after you have done all your other code, send the name
// key/value pair over the url using the header...
header("Location: someotherpage.html?fname=".fname ."&lname=".lname);
}
Once you have sent the values over the url to the someotherpage.html page you can use URLSearchParams to search the url for key parameters to get their paired value/s. window.location.search => The query string portion of the URL. This includes the question mark, and everything following. Use .get() to get the url's parameters using their key. Then you can assign them using javascript with the dataset attribute => element.dataset.fname = firstName.
let parameters = new URLSearchParams(window.location.search);
let firstName = parameters.get('fname');
let lastName = parameters.get('lname');
let div = document.getElementById('data');
div.dataset.fname = `${firstName} ${lastName}`;
Returns the following on someotherpage.html :

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

JQuery populating select box but after post options disappear

I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?
When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];

Sending dynamically created html content through email with PHP

I'm making a simple todo list: http://jsbin.com/pemeqeni/1/edit?html,output
I want to be able to email myself the list, and I'm wondering how to do this with PHP specifically. I thought about scraping the HTML with DOMdocument, but I think that will only get the content from the static HTML page, which will never have list items. My other idea is to dynamically create a bunch of hidden input fields in the emailForm and dynamically delete them just as I do with the list items. Are there any other options? What's the standard protocol for something like this?
Something like this should work for getting all list elements.
<script>
function getEachListElement() {
var testList = document.getElementsByClassName("todoBody");
for (var i = 0; i < testList.length; i++) {
document.writeln(testList[i].innerHTML);
}
}
</script>
Try it out by changing your form action to this
<form name="emailForm" method="GET" action="JavaScript:getEachListElement()">
Then you can just create a string that you pass to PHP to email to yourself.
Have you tried the php mail function?
ie
<?
mail( $email, $subject , $text );
?>
Instead of get I would use post then set up a php script you call where you put your values(strings) into variables using $_post and use the mail function to mail those variables(strings).
just to be more clear your html would look like this
<form name="emailForm" method="POST" action="getContent.php">
<input type="text" name="email" value="email"><input type="submit" value="send">
</form>
Your getContent.php would then look like this
<?
$myemail = "myemail#tada.com";
$email = $_POST["email"];
mail ($myemail, 'The shiz you wanted', $email);
?>

Categories

Resources