Passing submitted form info back into input field? - php

I've written a simple entry form that compiles information onto a database, and I'm having trouble with my required fields...
I use a form to process the data via post method if the user neglects to fill in a required field I would like to bring him back to the original form with his/her previous fields entered.
How to I pass info back into an input label? Is there an easy way to do this without any crazy scripts? I started with sessions but I realized I have no clue how to put the stored info from the session back into the input field so the user doesnt have to retype all of their info... Also would a cookie be better for this over session?
Thanks guys,
Arthur

When you post a form, all those variables are submitted into a global array named $_POST['input_name'] and available on the page posted to. A lot of times what I like to do if I'm doing it fairly quickly, is just make the value of those input fields equal the same as what would be posting.
For example lets say we have a desired username field but the form didn't validate for some reason and posted back to itself; we don't want them to have to enter it again:
<input type="text" name="username" value="<?php print $_POST['username']; ?>" />
Of course when they first load the page, the value will be empty so there is nothing there, but if for some reason it posts back, that "username" field will already contain entered information.
Even better is java script validation, as the form doesn't have to post back, but this will do the job just fine!

Since the user posts all your data to you, these values are also available in your scripts. So you can use them very easily in the case of text-fields, but a bit more work is required for select options, checkboxes and radio buttons:
<input id="myid" name="myid" type="text"
<?php echo !empty($_POST['myid'] ? "value=\"{$_POST['myid']}\"" ?> />
For radio buttons, select options and checkboxes you instead have to check the value to see if it corresponds with the entry you are currently outputting and print selected="selected".
When it comes to validation you can also have a JavaScript validation to give feedback sooner to the user about possible failures. Just remember to have the same validation on the server side in case someone doesn't have JavaScript enabled or submits it using JavaScript, thus bypassing your client side validation.

Not sure if this is the best way, but you could redirect to a "reload" page and use the values from POST or GET to reinput the existing fields. So first validate, the fields that are required and if any are missing, redirect to this page. Then the POST or GET will have all of the values the user filled in (and the missing required fields will already be blank) so you just loop through and load up the supplied info. Additionally, if they supplied incorrect info you could manually clear it and this will also allow you to mark the missing required fields.
Another option is put your validation in JS so you know the data is good before you submit. However, I'm not sure if there are security concerns with that or not.

I check to see if the post value has been set otherwise you can show a default value, then use a bit of jQuery to remove it when the input has focus
<input type="text" name="first_name" id="first_name" value="<?php if(isset($_POST['myid'])) { echo $_POST['myid'] } else { echo "Your Name" ?>"></input>
Here's the jQuery which will remove the default Your Name when the textbox has focus.
$(document).ready(
function(){
$.fn.clearDefault = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
// clear default textbox entries
$("#first_name"). clearDefault();
}
);

jQuery Validation Plug-in

<input type="text" name="username" value="<?php isset($_POST['username']) ? echo $_POST['username'] : null; ?>" />
will work fine

Related

Pass a user entered variable to php before POST?

I have a page that contains a form. This page also has a PHP script to set some variables.
These variables are then submitted as hidden values when the user clicks submit.
I have a requirement to take a users entered value (amount) and then set that as a variable inside the PHP , then post the form. Is this possible ?
I cannot just sent the form submitted value as it must go through a MD5 hash first in the PHP script. This is a requirment for Realex creditcard payments.
I was thinking this might be possible with JavaScript?
EDIT
Just to clarify , the page has PHP (simplified here for example)
<?php
$amount ="";
$tmp = "$timestamp.$merchantid.$orderid.$amount.$curr";
$md5hash = md5($tmp);
$tmp = "$md5hash.$secret";
$md5hash = md5($tmp);
?>
All of the above variables are pre-defined and dont change, however the amount is dependant on what the customer enters.
The form is on the same page as the above , so when the customer enters a value , then hit submit ... this along with the md5 hash above is sent.
<form>
<input type="text" name="donate_amount" value="">
<input type="hidden" name="AMOUNT" value="<?=$amount?>
</form>
but Im not sure how to do this dynamically before posting.
I'm not sure if I'm getting this correctly without seeing code, but from what I got from it what I think you want to to is save whatever it is to a session.
so if its coming from input
$_SESSION['derp'] = Hash::howeveryouhash($_POST['derp'])
or if hash happens after input is gotten just save the hashed input to a session?
I'm not sure if this what you meant, but if it is, be sure sure to reference the php manual to insure proper use of $_SESSION!
You need to know the final amount before you create the hidden form Gary. There's no point creating the hash without it.
You should ask the user for the amount they wish to donate on the previous page. Then you can present a final "Donation Overview" page containing the hidden form, and the "Proceed to Payment" button.
Whatever you end up implementing, don't put the Realex shared secret in the javascript on the page! This must be kept secured on the server side.
How about doing this:
<input type="text" name="amount" onchange="ajaxFunction(this)" value="" />
Then when the input field changes the function ajaxFunction calls a PHP script sending the value. In the PHP script you can store the value in $_SESSION['amount'] for later use.
function ajaxFunction(obj) {
$.post("store_amount.php", { amount: $(obj).val() } );
}
Requires jQuery.

Reload php form data after Server side validation

I am doing server side validations for my html values. However when server side validation fails and I return back to the page, the form data is cleared. Is there anyway to do save and reload the form data in php without using any framwork?
Just put the submitted value (if there is any ) inside your value="" like this:
$set = isset($_POST['username']) ? $_POST['username'] : '';
The above is called the ternary operator. And, as I have done it, it will check if someone has already submitted a form with attribute "username" ($_POST['username']) in your form, if yes, then it sets the the value of that form to a variable called $set otherwise it just sets it '' nothing.
Now, all you have to do is just put the $set variable inside like: value=" <?= $set ?> ">
Well, sure. Assuming that you're submitting to a different script, and need to be directed back to your page with the form, use PHP Sessions. Save all of the data that you need to reload in the session, and then on your page use the session data to pre-populate the form if it's there. Once you're done using it (i.e. they've successfully completed their form), then you can clear the session on a subsequent interaction.
Yes,
Say you have your input:
<input type="text" name="email" />
If you did this:
<input type="text" name="email" value="<?php echo $_POST['email']?>"/>
It would repopulate with whatever they typed in.
Send the values to the server using an AJAX call, that wont refresh the page leaving your data intact in the page.

Unable to Insert Data into MySql Table using username from another $_POST function

echo "Hello : ".$_SESSION['doc_username'];
//username sent from a different page by post method
$username = $_POST['username'];
echo "<p><strong>Showing Health Information for : </strong>";echo $username; "</p>";
if($_POST['submit'])
{
$height = mysql_real_escape_string($_POST['height']);
$weight = mysql_real_escape_string($_POST['weight']);
if($height && $weight)
{
require "dbc.php";
$query = mysql_query("UPDATE patient_info SET
height='$height',weight='$weight' WHERE username='$username'");
echo "Patient Data Saved!";
}
else
{
echo "All fields are required!";
}
The problem with this code is not in the mysql query. I have already checked it for syntax errors using phpcodechecker and there was none. There were more variables to be inserted into the database but height and weight will do for example. My problem is I am getting the username from a different page by POST method and I cannot save it in a way that it could be used by the "submit" value in this form to enable updating of that particular username. Because the username from the other form which $username cannot be referred to within the $_POST in this page, thus the username variable is blank when I click the submit button. How can I get a username sent from another page to this page by POST to be used in this form in the UPDATE query. The form does send the username to this page successfully which is proven when I can echo the username out. But it cannot be used by the form in this page. Please help as I am very new to PHP codes and I'm trying the best that I can.
On the initial page, add a hidden form element named "username" with the value you want to carry over into the form submission.
<input type="hidden" name="username" id="username" value="the.user.name">
You may store user name in session on request when it passed, or add to getparam of request or in hidden element of form:
<form action="procces.php?username={real_user_name}">
OR
<form>
<input type="hidden" name="username" id="username" value="{real_user_name}"/>
...
</form>
<input type="text" name="username" value="<?php echo $_POST['username']; ?>" />
The username in first page was transferred to another paged where you can edit it
As second page also contains a form so we also need to add username field int as when it will be posted the username will also be sent.
This had to be inserted into the 2nd form to retain the data sent from the previous in the previous page so that it can be used for the query in mysql.
First of all replace the line:
From:
if($_POST['submit'])
to:
if (isset($_POST['submit']))
If you are using a combobox then check that you have provided the name parameter in its markup like:
<select name="submit">
...
</select>
[EDIT]
After analyzing the code it is found that the HTML markup
was written after form element. I think this is the issue. Rest
appears to be Ok.
Hope this will solve the issue.
You may the user name in the session (supposed you have one, if not, you seriously should anyway):
Populating a form field like #tslocum suggested also needs to get the user name from somewhere. This is a quite common solution, but where does the user name come from?
There might be some time between submitting the name and rendering the current page, so as this is stateless but you need a state (State "we have a given username already") within that page during rendering and processing, take a look at $_SESSION global variable.
my approach:
Post 1:
....
$_SESSION['currentUser'] = $_POST['username'];
// you need some checks over here, don't use
// that as typed here, left out just for clearness.
... some time
Post 2:
...
$username = $_SESSION['currentUser'];
// again some checks over here!
read about $_SESSION in the php manuals.

Required field display error message on form

I have a form that I need to have required fields filled out. I know to use the code below to verify if the field is blank:
<?php
if (!empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
My question is, how do I get the error message to display on the form page, saving all the data already entered in the form. Example: I fill out all 15 fields on the form, excluding the required field. When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.
I am not sure on the code to do that, or where to put it. On the form, or on the script that executes the form?
use client side javascript validation first, then php server side validation.
Why you use !empty you can use empty for best result like
<?php
if (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
Actually you should be first set HTML5 validation like
<input type="text" name="abc" required="">
You can set custom error message for required field like
<input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">
Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.
Thanks.
Without knowing the structure of your pages, it's hard to give an exact answer, but here's a general process flow that should help:
Form is submitted to processor
Processor validates inputs
if inputs are good, processor redirects to next page
if inputs are not good, processor should send error text and form data back to the routine that builds/displays the form.
IMHO, the processor should not echo anything. All display should be handled by the script that builds the form.
Without coding it for you, that's the best answer I can give :-)

Remember form value when return back to submit due to some error

After filling the form when submit, accidentally due to some filling error ,the form is not submit and return to back,in this condition the value of all text box is blank. i want to stable value of all fields in this condition . I'm using php with smarty framework. Please reply with solution as soon as possible.
Thanks.
If the form is submitted to the page that contains it then you will have access to the submitted values, and can use them to populate your form. For example, if you are submitting the form via POST:
<input name="something" value="<?=$_POST['something']?>" />
If you are submitting the form to a different script, you could send the values back to the page with the form as URL parameters, or you could use temporary session variables, and unset them when the input passes whatever validation you are using:
$_SESSION["temp_something"] = $_POST["something"]; //In form processing script
Then in your form:
<input name="something" value="<?=$_SESSION['temp_something']?>" /> <!--In form-->
You can fill the form fields, on the second round, by filling the content inside the value attributes of html tags, like so:
<input type="text" value="<?php echo $_REQUEST['test']; ?>" name="test">
Pay attention: this is a fast and simple solution. It gives you an idea. In good web programming practice you should sanitize the form data received by client in order to avoid security issues.

Categories