I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?
I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""
I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.
I tried using
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?
Form code:
echo ' <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
Name: <input name="name" type="text" /><br />
Email: <input name="email" type="text" /><br />
Phone Number: <input name="phone" type="text" /><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"></textarea><br /><br />
<input type="submit" name="submit" value="Submit Email"/>
</form></div>
<div style="clear:both;"></div><br /><br />';
and the vaildator:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!is_numeric($phone)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
} else {
mail( "email#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!
Second: you could(should?) use a hidden field instead of specifing it in the action?
But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?
You could use ajax to fix it(I believe plain old HTML has this side-effect?).
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.
In case you display the form again, you could set the values of the inputs like this:
$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.
If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:
<input type="hidden" name="date" value="'.$date.'"/>
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.
Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:
If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:
Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.
Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.
Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.
A very basic form handling script would look something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] = 'POST') {
# do this only if actually handling a POST
$field1 = $_POST['field1'];
$field2 = $_POSt['field2'];
...etc...
if ($field1 = '...') {
// validate $field1
}
if ($field2 = '...') {
// validate $field2
}
... etc...
if (everything_ok) {
// do whatever you want with the data. insert into database?
redirect('elsewhere.php?status=success')
} else {
// handle error condition(s)
}
} // if the script gets here, then the form has to be displayed
<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>
?>
Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.
As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.
first, a few general changes:
change
<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
to
<form method="post" action="'.$_SERVER["PHP_SELF"].'">
<input type="hidden" name="data" value="'.$date.'" />
the answer to your original question:
set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);
For example: the name field
<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />
Related
I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>
Hey i have having a problem i just found working with session i am using at the moment firefox 23 but i have check that on some other browsers as well.
I have created a simple code where i have created a form and just opened a session and i have noticed that once i have submit the form and then click on "Go Back" to return to the page the info i have inserted is not saved on the browser.
Normally when you submit a form once you go back the data you have entered is saved and you can just edit the inputs and resent it but when i have used session_start() on the page that function stopped working.
Well i am guessing maybe the browser save the form data in sessions as well and once i use it in php it's somehow effect the normally way the browser work.
I hope someone know how i can fix that i know you are able to save sessions with html5 and javascript now but i would rather do that with php.
Attached below is the code i have been using:
<?php
session_start();
// store session data
$_SESSION['name']= "name";
?>
<form method="post" action="index.php">
<input type="text" name="email" placeholder="Email" /><br />
<input type="text" name="name" placeholder="Name" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
The browser refilling the form is simply that, the browser. This is not something you should rely upon for form re-population.
Your PHP code does not attempt to refill the form by printing anything within the input value="" attributes.
Generally when a form is submitted a programmer will validate the submitted values, store them in some fashion (the session is fine) and if they need them to reappear on the form they will print those values back out like I described.
I think you want to put the CORRECT fields back into the form values and blank out the incorrect ones. You don't have to use sessions:
<?php // formx.php
// accept POST variables
$fld1 = isset($_POST['fld1']) ? $_POST['fld1'] : "";
$fld2 = isset($_POST['fld2']) ? $_POST['fld2'] : "";
// edit variables
$errmsg = "";
if (!$fld1 == "") { if($fld1 <> "1") { $errmsg .= "fld1 is not 1<br />\n"; $fld1 = ""; } }
if (!$fld2 == "") { if($fld2 <> "2") { $errmsg .= "fld2 is not 2<br />\n"; $fld2 = ""; } }
if ($errmsg == "") { $errmsg = "Values accepted"; }
// output form
$body = <<<EOD
<html>
<body>
<div>%s</div><!-- errmsg -->
<form name="formnm" action="formx.php" method="post">
Enter "1" <input type="text" name="fld1" value="%s" /><br />
Enter "2" <input type="text" name="fld2" value="%s" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
EOD;
printf($body, $errmsg, $fld1, $fld2);
?>
I have a form which the user enters data eg first name and last name etc. I have PHP validation which checks for empty field. The problem is when the submit button is clicked, the whole form data is erased when a field is left empty.
I tried this method below.
<input type="text" value="<?php echo $_POST["UserName"]; ?>"" name="UserName"
id="UserName" size="20" />
But when the form loads for the first time, inside the text box is this
<br /><b>Notice</b>: Undefined index: UserName in ...... on line <b>477</b><br />
Is there a method to stop the form from being cleared? or to echo the data into the fields?
replace this :
value="<?php echo $_POST["UserName"]; ?>"
in your code with this :
<?php if(isset($_POST["UserName"])) echo $_POST["UserName"]; ?>
The issue here is that you're not checking whether $_POST["UserName"] is initialized, and when it is not, you'll throw the error. Check with isset:
<input type="text" value="<? if isset($_POST["UserName"]) { echo $_POST["UserName"]; } ?>" name="Givenname" id="Givenname" size="20" />
Check if $_POST["UserName"] isset, Try this:
<input type="text" value="<?php echo isset($_POST["UserName"]) ? $_POST["UserName"] : ''; ?>" name="Givenname"
id="Givenname" size="20" />
I think you are using Reset button like this:
<input type="reset" />
Try this:
<input type="submit" />
If you are trying Second one then use required in every input like:
<input required type="text" />
Your form is not being cleared or erased. But you are loading a NEW page with a NEW form.
Your attempt to load the new form is a good one, but you need to change
<input type="text" value="value="<?php echo $_POST["UserName"]; ?>"" name="UserName" id="UserName" size="20" />
into
<input type="text" value="<?php echo isset($_POST["UserName"])?$_POST["UserName"]:""; ?>" name="UserName" id="UserName" size="20" />
So remove the second value=" and the corresponding " which should have never been there. And check if the variable is available before trying to echo it.
In addition to doing this, you might also want to do client side validation in Javascript on top of the server side validation. (Never only do client side validation, by the way, as that can be fooled by end users.)
What you can do is to change your <form> tag into this:
<form action="..." method="post" onsubmit="if (document.getElementById('UserName').value == '') { alert('UserName is still empty'); return false; }">
This will prevent the form from being sent to PHP when UserName is still empty. And thus prevent from the page being reloaded and the form being cleared.
PHP forms will often discard entered data upon error validation, even when echoing it in the input field caches the entry on successful submit, and it is understandable that erasing disallowed data would be the default behavior. However, it can be a real hardship to retype large amounts of text in a textarea, and its sudden vanishing may come as an unwelcome surprise to the user, especially when due to a simple reason such as an over-the-character-number limit.
Setting the $_POST['UserName'] value with the error validation should preserve the field input without allowing its process. The example uses a variable to cache the data and echo it into the input field.
Update: The script has been updated to include multiple submit buttons for the same form, as well as the option for a success message array.
Update: The script has been updated to include an exit() option as well as a textarea.
UserName and First Name allowed characters are defined and will
trigger an error with uppercase A-Z or special characters.
UserName uses the error array, while First Name uses exit() to stop
the script altogether.
Textbox allowances also will trigger an error with uppercase A-Z or
special characters, and use exit() to stop the script.
The form data will be preserved on error message, exit() page return, and successful send.
The form results are printed on successful send.
<?php
/* Define variables and set to empty values.*/
$username=$first_name=$textbox='';
/* If using non-array success variable, initialize it as a string:
$success='';
Otherwise, define as an array. */
/* Submit button is clicked, start validation.
Separate multiple submit buttons (for the same form) with || (|| = OR):
*/
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
// Define error and success messages as arrays to display in a list.
$error=array();
$success=array();
// Validate user input and error characters not lowercase a-z or 1-9.
if (!empty($_POST['UserName'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $username)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['UserName']))) {
$username=trim(htmlspecialchars($_POST['UserName'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
$error[]='User Name can only contain lowercase a-z and 0-9.';
$username=$username;
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether:
$username=$username;
exit ("Username may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
*/
}
}
else {
$error[]="Please enter a User Name.";
}
if (!empty($_POST['first_name'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
if (preg_match("/^[a-z0-9]+$/", $first_name)) {
/*
if (preg_match("/^[a-z0-9]+$/", trim($_POST['first_name']))) {
$first_name=trim(htmlspecialchars($_POST['first_name'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$first_name=$first_name;
exit ("First Name may only contain lowercase a-z and 0-9. Use the Back-button to try again.");
/*
$error[]='First Name may only contain lowercase a-z and 0-9.';
$first_name=$first_name;
*/
}
}
else {
$error[]="Please enter a First Name.";
}
if (!empty($_POST['textbox'])) {
/* Trim outside whitespace and sanitize user input.
A custom function or purifier could well be used. */
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", $textbox)) {
/*
if (preg_match("/^[a-z0-9\ \(\s*\n){2}]+$/", trim($_POST['textbox']))) {
$textbox=trim(htmlspecialchars($_POST['textbox'], ENT_QUOTES));
}
can be placed here instead, however input data will likely not be preserved on error. */
// Data is acceptable, continue processing...
}
else {
// Data is not accepted, set value to prevent loss on error and echo input without processing.
/* Use exit() instead of $error[] to help prevent form input loss while exiting the script altogether. */
$textbox=$textbox;
exit ("Textbox input may only contain spaces, lowercase a-z, and 0-9. Use the Back-button to try again.");
/*
$error[]='Textbox input may only contain spaces, lowercase a-z, and 0-9.';
$textbox=$textbox;
*/
}
}
else {
$error[]="Please enter Textbox content.";
}
// If no errors, process data.
if (empty($error)) {
if (isset($_POST['submit_one'])) {
/* Sanitized submit button per rule #1: never trust user input. Remove sanitization if it causes a system error.
Reiterating ($_POST['submit'] is helpful when using multiple submit buttons.
Wrap each function in the additional submit isset, and end functions with closing (empty($error) else statement. */
$_POST['submit_one']=trim(htmlspecialchars($_POST['submit_one'], ENT_QUOTES));
/* Post data or send email, and print success message.
The array is option. Do not define as an array or use[] to use as a simple variable. */
// Processing data here, for example posting to a database ...
$success[]="The submit_one Send Form request has been processed!";
}
if (isset($_POST['submit_two'])) {
$_POST['submit_two']=trim(htmlspecialchars($_POST['submit_two'], ENT_QUOTES));
// Processing data here, for example sending an email ...
$success[]="The submit_two Process Form request has been sent!";
}
}
/* If errors, show error message.
The exit() option ends the script at the validation check .*/
else {
$error[]="Please correct the errors and try again.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.wrapper {margin: 2% auto; width: 500px;}
textarea {text-align:left;}
</style>
</head>
<body>
<div id="anchor" class="wrapper">
<div>
<form name="data_form" action="#anchor" method="post">
<table>
<tr>
<td colspan="2">
<label for="UserName">User Name</label>
<br>
<input type="text" name="UserName" id="UserName" size="20" value="<?php echo $username; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="first_name">First Name</label>
<br>
<input type="text" name="first_name" id="first_name" size="20" value="<?php echo $first_name; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="textbox">Textbox</label>
<textarea name="textbox" id="textbox" style="height:100px; width:98%;text-align:left;"><?php echo $textbox; ?></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit_one" id="submit_one" value="Send Form">
</td>
<td>
<input type="submit" name="submit_two" id="submit_two" value="Process Form">
</td>
</tr>
</table>
</form>
</div>
<div>
<?php
/* Print errors as a list or print success message.
Separate multiple submit buttons with ||. */
if ((isset($_POST['submit_one'])) || (isset($_POST['submit_two']))) {
if (!empty($error)) {
echo '<h4>The form was not sent due to the following errors:</h4>
<ul>';
foreach ($error as $message) {echo '<li>'. $message . '</li>';
}
echo '</ul>';
}
/* Print success confirmations as a list for processed input. */
else {
echo '<h4>The form has been sent!</h4>
<ul>';
foreach ($success as $message) {echo '<li>'. $message . '</li>';}
/* If using a success variable without defining it as an array,
initialize it as a variable at the top of the script,
then print variable without <ul>s and foreach loop:
echo '<p>' . $success . '</p>';
*/
echo '</ul>
<h4>Processed Data:</h4>
<ul>
<li>User Name: ' . $username . '</li>
<li>First Name: ' . $first_name . '</li>
<li>Textbox: <br>' .
/* Replace $textbox new lines with <br> tags. */
nl2br($textbox) .
'</li>
</ul>';
}
/* Unset foreach loop data. */
unset($message);
}
?>
</div>
</div>
</body>
</html>
I'm using CKEditor to create a html mailer in which a contact form is being sent to email.
The problem is, there is no value being received on submission of that form in email.
Contact Form in E-Mail (code)
<form action="http://techindiainfotech.com/mail.php" method="post" name="test">
<p>Your Name: <input maxlength="75" name="name" size="75" type="text" /></p>
<p>Mobile Number: <input maxlength="10" name="mobile" size="10" type="text" /></p>
<p>Business Name: <input maxlength="100" name="business" size="100" type="text" /></p>
<p><input name="sub" type="submit" value="Submit" /></p>
</form>
Handler - mail.php
if ($_POST['sub'] != '') {
unset($_POST['sub']);
echo "Details received:<br>";
foreach ($_POST as $val) {
echo "$val<br>";
}
} else {
header("Location: http://www.techindiainfotech.com/files/contact_us.php");
exit();
}
Screenshot from gmail's Message Text Garbled
if ($_POST['sub'] != '') {
unset($_POST['sub']);
The above code means: if $_POST['sub'] is not an empty string, evaluate the statements below.
If your form wasn't submitted, $_POST['sub']; will be undefined and PHP will throw an error saying Undefined index.
I'd use isset() instead to properly check if the form was submitted or not.
if (isset($_POST['sub'])) {
# code ...
}
The following should work:
if (isset($_POST['sub']))
{
unset($_POST['sub']);
echo "Details received:<br>";
foreach ($_POST as $val)
{
echo "$val<br>";
}
}
Your form is so simple and the $_POST loop, that it narrows down the error sources:
file base: scripts are not in the folder you expect
CKEditor throws out HTML, either you strip it or,... have a look into the HTML sourcecode.
Use print_r($_POST); at the beginning of mail.php
enable PHP debugging / error reporting: http://blog.flowl.info/2013/enable-display-php-errors/
if you have javascript we cannot see in your sample code, remove it for further testing
Update:
the CKEditor changes your inputs in a way that they are not anymore labeled by name attributes or renders the form in any other invalid form (don't think that's the problem)
I copied your sample code onto my webserver and it's working. You might have something in your real code that doesn't appear in the code above.
Everything was fine except for the one, the form action attribute.
I'm submitting the form to http://techindiainfotech.com/mail.php but due to .htaccess it is being redirected to http://www.techindiainfotech.com/mail.php and that's why the request has been lost (I'm not getting the appropriate word here).
So, I just need to change in my action attribute which is, submit my form to http://www.techindiainfotech.com/mail.php not to http://techindiainfotech.com/mail.php.
I have a basic contact form on my website and I am trying to add the PHP ucwords() function of PHP to the form for the users first_name and last_name fields so they capitalize the first letter correctly. How would I add this to the actual HTML form?
Edit: I want these changes to be applied only after the user submits the form. I don't really care about how the user types it in. I just need someone to actually show me an example.
Like how would I add the PHP ucwords() code to this simple form?
<!DOCTYPE html>
<html>
<body>
<form action="www.mysite.com" method="post">
First name: <input type="text" name="first_name" value="" /><br />
Last name: <input type="text" name="last_name" value="" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
I am assuming I do something like value='<php echo ucwords() ?>' but I have no idea how?
Thanks!
When user submit the form you can access the submitted information through $_POST variable [because method="post"] of PHP and in action you have to specify the actual page where you need the submitted information to be process further
<?php
// for example action="signup_process.php" and method="post"
// and input fields submitted are "first_name", "last_name"
// then u can access information like this on page "signup_process.php"
// ucwords() is used to capitalize the first letter
// of each submit input field information
$first_name = ucwords($_POST["first_name"]);
$last_name = ucwords($_POST["last_name"]);
?>
PHP Tutorials
Assuming short tags are enabled:
$firstName = 'Text to go into the form';
<input type="text" name="first_name" value="<?=ucwords($firstName)?>" />
Otherwise as you stated
<input type="text" name="first_name" value="<?php echo ucwords($firstName); ?>" />
Assuming you wanted to do it without a page refresh, you need to use Javascript. Simplest way would be to add an onkeyup event to the input field and simulate PHP's ucwords functions, which would look something like...
function ucwords(str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
Edit: In response to your edit, if you want to get the value they sent with ucwords applied, all you need to do is $newVal = ucwords($_POST['fieldName']);