I have 2 forms for a shopping cart. When they go back I would like the input fields to be filled with info they originally put in before submitting.
1st uses basic form fields to submit billing and shipping info.
2nd is used for CC info. What I would like to do is in that second form have a BACK BTN that will populate all the fields from the first form with the data they entered.
I have a PHP variable $response with an array returning values, but I don't believe they are all included. It brings back a token from PayPal. I think that might be purposely for security reasons. Perhaps I can store them locally in some JS variables?
I tried the below with no results:
<input name="BILLTOFIRSTNAME" id="billtofirstname_id" value="<?php echo $response['BILLTOFIRSTNAME'];?>"/>
use this in your first page -
session_start();
$data = array("input1"=>"value1","input2"=>"value2");
// store any data in this array
$_SESSION['data'] = $data;
Now if user returns to this page -
if(isset($_SESSION['data'])){
// check if data is available
$value1 = $_SESSION['data']['input1'];
}
else{
$value1 = '';
}
In your input's html add this -
<input name="input1" value="<?php echo $value1?>" />
Here you can use local storage variable
<button onclick="store()" type="button">first form submit</button>
<script type="text/javascript">
function store(){
var billtofirstname_id= document.getElementById("billtofirstname_id");
localStorage.setItem("billtofirstname_id", billtofirstname_id.value);
}
</script>
<button onclick="back()" type="button"> Second form back button</button>
<script type="text/javascript">
function back(){
document.getElementById('Id').value=localStorage.getItem("billtofirstname_id");
}
</script>
Related
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
}
?>
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";
}
I have one input-text box with a submit button. By using an autocomplete method when I search for related data, if data is in database it should do the search, otherwise it should be inserted in database when I click submit. Here in my code I am getting the database result in "source" using ajax in JS.
<?php $search = "<script>source</script>";
if(count($search) > 0){
$onclickEvent = "onclick='return searchQuestionName();'";
}else{
$onclickEvent = "onclick='return InsertQuestionsInfo();'";
} ?>
<div class="ui-widget">
<input type="text" id="questionname" name="name" placeholder="Search through Questions" required=""/>
</div>
<button type="submit" id="FormSubmit" <?php echo $onclickEvent;?> class="mc-btn btn-style-1" style="width:100px;">Submit</button>
Below is my autocomplete Script:
<script>
$( "#questionname" ).autocomplete({
source: rootUrl+"includes/ajax/ajax_chat.php?action=searchQuestionName"
});
</script>
From My understanding, You cannot define the onclick event before you start typing search term.
You have 2 choices,
1/ textbox id questionname, on blur you send an ajax request and find the count. then bind the click event to the submit button according to the count you get from ajax.
2/ Just submit this form to a php file and write your business flow.(find search term's count, if no count just insert the search term before proceed you business logic).
I am trying to get a form to submit automatically, which feeds a username and password to another form.
If I remove the javascript and just have the form display on the screen, and manually click the Submit button, the result is I get automatically logged in on the resulting page. This is the result I want.
If I leave the javascript in place, it actually doesn't automatically log me in but it does pass across the username and password pre-filled on the resulting page, then I have to click Submit on the resulting page.
How can I make it automatically submit the form to work the same way as a user actually hitting the submit button? Also I understand that this may not be the most secure way to pass a username and password across, but this is for a special use case.
Note: MyForm is a php page, and I am submitting to an aspx page.
Here is code of what my form would look like:
<form id='myForm' method='post' action='https://blah.com/Login.aspx'>";
<p>Username: <input value='usernameHere' name='Username' type='text' id='Username' data-index='0' maxlength='255' placeholder='Username' class='loginUsername' />";
<p>Password: <input value='passwordHere' name='Password' type='password' id='Password' placeholder='Password' />";
<p><input type='submit' name='btnSignIn' value='Sign In' id='btnSignIn' />
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
Thank you.
I suspect there are other issues at play, as using JS to submit the form should replicate a native browser submit.
You can try simulating clicking the 'submit' button via JavaScript:
JavaScript:
document.getElementById('btnSignIn').click();
jQuery:
$('#btnSignIn').click();
You can use onload method for javascript
function submitForm() {
// **NOTE** set form values first
document.getElementById('myForm').submit();
}
window.onload = submitForm;
Or with jQuery if you want:
$(function(){
submitForm();
});
or with tag attribute
he typical options is using the onload event:
<body onload="javascript:submitForm()">
.
.
As the problem is supposed "post a form through php" . It may be achived by using PHP€™s functions fsockopen() and fputs() to send properly formatted data to a remote server. Here is a sample of code :
<?php
//create array of data to be posted
$post_data['Username'] = 'XYZ';
$post_data['Password'] = '********';
$post_data['btnSignIn']="Sign In";
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//we also need to add a question mark at the beginning of the string
$post_string = '?' . $post_string;
//we are going to need the length of the data string
$data_length = strlen($post_string);
//let's open the connection
$connection = fsockopen('https://blah.com', 80);
//sending the data
fputs($connection, "POST /Login.aspx HTTP/1.1\r\n");
fputs($connection, "Host: https://blah.com \r\n");
fputs($connection,
"Content-Type: application/x-www-form-urlencoded\r\n");
fputs($connection, "Content-Length: $data_length\r\n");
fputs($connection, "Connection: close\r\n\r\n");
fputs($connection, $post_string);
//closing the connection
fclose($connection);
?>
The above codes do post your form now to get redirect to that page , use simply
header('location :https://blah.com/Login.aspx ');
I am working on a small application in which I need to use array as database. I have a form containing name and age field in php file named index.php. My Index.php looks like this:
<pre><code>
<?php
session_start();
$_SESSION['var'] = 0;
?>
<html>
<body>
<form action="weloome.php" method="post">
Name : <input type="text" name="name"/><br/>
Age : <input type="text" name="age"/><br/>
<input type="submit" name="submit" value="Submit" onsubmit=
"<?php $_SESSION['var'] += 1; ?>/>">
</form>
</body>
</html>
</code>
In this code I Use session variable var which gets increment on the onsubmit event of form. It gets increment because I want all values to be stored in array called db_array().
This is second file welcome.php
<?php
session_start();
$db_array[$_SESSION['var']][0] = $_POST['name'];
$db_array[$_SESSION['var']][1] = $_POST['age'];
print_r($db_array);
?>
Want to Add more Record? Click Here
But the problem is that $_SESSION['var'] = 0; initializes with zero every time
when user click on link on above page. That is why only last record is shown because array is overwritten. Any Solution to this problem?
Thanks in advance.
Add a conditional:
if (!isset($_SESSION["var"]) {
$_SESSION["var"] = 0;
}
This will only initialize the session only if it hasn't been initialized before.
is weloome the correct name? is that a typo?
You can use this check,
if(session_id()=="")
{
session_start();
$_SESSION['var']=0;
}
this will only execute if session is not found.
In PHP versions 5.4* and later, this is the most efficient way to see if session is already started or not.
if(session_status() !== PHP_SESSION_ACTIVE)
{
// session is not started yet
session_start();
}
Here you go: If your variable is empty, it will initialize it with zero, else it will remain the same ;-)
<?php
if(!$_SESSION['var'])
$_SESSION['var'] = 0;
?>
if you want to develop this further, you could use the serialize functions to convert it into something you can store, in a cookie perhaps, or a file, or a database..
the serialize function converts the array into a string that can be stored. Sort of looks like json.
If you got any more questions, is there a way to notify me? can i follow people like on facebook/twitter?