Passing variables through three pages - php

I would like to pass variables through out three pages.
The method I am currently using is:
Fist Page has a form e.g. input type=”text” name=”username”
Second page receives input from form on first page with the $_POST function
e.g. $username=$_POST[“username”]
In order to keep the information from the first page stored, I created a session on the second page, and stored the input in it, e.g. as follows:
$_SESSION[“username”]=$username
I then navigate to the third page and start my session. If I echo the stored input from my session, the server returns “undefined variable username ”. I’m guessing this is so, because the variable $username is by definition $_POST[“username”], and in this case, there is no input for that post (being on the third page).
Of course I have tried converting the variable $username in a string and/or text with the print()/print_r() function. Doesn't change anything.
Does anyone have any solutions or workarounds to this issue?
I have come up with an unelegent way to solve the one problem: just recreate a copy of the form on the first page in the second page with the value=$_POST[“username”]…….but I need this to be a session, as these three pages are not linear (in other words, not steps 1,2,3, but steps 1,2,1,3 etc).
If it helps: this is a registration form (without passwords) with three pages. In the end, one must be able to navigate back to the pages to check ones inputs (so the data needs to be stored somewhere in order to call it up in the input fields).
Code page one (Inputs are in tables, left column specifies the what the Input is, right column the entry field):
<table>
<tr>
<td class="table_column_1"><p>Title </p></td>
<td>
<p><select name="title" class="dropdown" style="width:145px">
<option>Bitte waehlen</option>
<option value="Frau">Mr</option>
<option value="Herr">Mrs</option>
</select></p>
</td>
<tr>
<td class="table_column_1"><p>First name: </p></td>
<td><p><input type="text" name="firstname"</p>
</td>
</tr>
<tr>
<td><p>Surname: </p></td>
<td><p><input type="text" name="surname" /></p></td>
</tr>
<tr>
<td><p>Email: </p></td>
<td><p><input type="email" name="email" /></p></td>
</tr>
<tr>
<td><p>Company: </p></td>
<td><p><input type="text" name="company" /></p></td>
</tr>
<tr>
<td class="table_column_1"><p>Department: </p></td>
<td><p><input type="text" name="department" /></p></td>
</tr>
</table>
Code page two:
<?php
//Change variable to text/string
$title=print_r($_POST["title"]);
$firstname=print_r($_POST["firstname"]);
$surname=print_r($_POST["surname"]);
$email=print_r($_POST["email"]);
$company=print_r($_POST["company"]);
$department=print_r($_POST["department"]);
if ($title != "Bitte waehlen" && $firstname != "" && $surname != "" && $email != "" && $company != "" &&$department != ""){
session_start(1);
echo "Session: RUNNING";
//list for registration values
$_SESSION["registration"]="YES";
$_SESSION["title"]=$title;
$_SESSION["firstname"]=$firstname;
$_SESSION["surname"]=$surname;
$_SESSION["email"]=$email;
$_SESSION["company"]=$company;
$_SESSION["department"]=$department;
//Test session department and variable firstname validity
echo $_SESSION["department"];
echo $firstname;
}
else{
session_start(1);
$_SESSION["registration"]="NO";
echo "Session: NO";
header("location: registration.php");
};
?>
Code page three:
<?php
session_start(1);
echo "Session: RUNNING";
//Check if session department data is returnable => no
echo $_SESSION["department"];
?>

You'll have to show your code, but basically, this should work:
session_start();//before ANY output is sent to the client!
if (isset($_POST['username']))
{
$_SESSION['username'] = $_POST['username'];
}
if (!isset($_SESSION['username']))
{
//redirect, or present user with error message
}
$username = $_SESSION['username'];
This sets $_SESSION['username'] to the value of $_POST['username'] if that post value was sent, and assigns the value of $_SESSION['username'] to $username in all cases. if neither $_POST or $_SESSION have a username set, then there is an unexpected problem, and you should redirect, or show the user an error message...
After your code was posted, a couple of issues became obvious:
session_start expects no arguments, you're passing 1.
session_start can only be called when the headers haven't been sent (ie: no output), you're calling print_r, which creates output.
Don't use the closing ?> tag, if your script only contains PHP (see php.net if you want to know why)
Make sure there is no whitespace before the opening <?php tag
Functions return values for a reason: session_start returns false if the session couldn't be created: check return values
This means that your page2.php script should look like this, more or less:
<?php
if (!session_start())
exit('Output has already been sent!');//check for whitespace, use output buffering...
if (isset($_POST['title']) && $_POST['title'] !== 'Bitte waehlen')
{
$_SESSION['title'] = $_POST['title'];
$_SESSION["registration"]="YES";
//avoid notices, always use isset:
$_SESSION['firstname'] = isset($_POST['firstname']) ? $_POST['firstname'] : null;
}
else
{
//form wasn't submitted, or the title was "Bitte waehlen":
// show error message, or redirect
}

As far as I can understand you are using register globals.
Now that is your first error. Don't use it. Just don't.
Then, you are storing the username in a session, so now you can access it using
$_SESSION['username']
Also, when storing data in a session you also need to call session_start(); before assigning any data to your session.

Related

No data submitted from a form

I have created a simple HTML form containing just one field. When I press submit some PHP code that I have written gets called and outputs text that would include submitted data if everything was working. But no submitted text gets printed by the PHP. The form has been created on a Godaddy HTML page and the form is as follows:
<FORM BORDER="1" action="http://www.bestpro.com.au/wordpress/PHB_action.php"
method="post" enctype="application/x-www-form-urlencoded"
eenctype="multipart/form-data" name="PHBForm" accept-charset="ISO-8859-1"
ienctype="text/plain">
<TABLE>
<TR>
<TD>First name:</TD><TD><INPUT type="text" name="firstname" id="firstname"></TD>
<TD></TD><TD></TD>
<TD> </TD><TD> </TD>
</TR>
<TR>
<TD> </TD><TD> </TD>
<TD> </TD><TD></TD>
<TD> </TD><TD><input type="submit" value="Submit"></TD>
</TABLE>
</FORM>
The PHP code output starts as follows:
This is where we end up.
Using `$_POST["firstname"]` which outputs nothing.
Using `htmlspecialchars($_POST["firstname"])` which also outputs nothing.
Question:
The PHP output doesn't include the value that I entered into the field.
Can anyone see what I am doing incorrectly?
I see nothing wrong here, so I can only assume it is something wrong with how you output it on your PHB_action.php page.
You say that you're placing $_POST['firstname'] on your page, but have you actually made sure to echo or print it to the page?
You can do this like so:
echo $firstname = $_POST['firstname']; // notice the echo placed before
or
$firstname = $_POST['firstname'];
print("$firstname");
EDIT:
I've notice you have put your post data inside of single quotation marks when echoing out to your page.
You must concatenate on your data rather than putting them inside of single quotes when echoing, like so:
echo 'Using' . $_POST['firstname']; // notice the dot in between the string and the post data.
Either that, or you have not installed PHP correctly (or at all) onto your server.
Hope this helps
So, this is pretty straight forward and I have written it up and will explain each bit as i go.
The PHP you need for this is:
<?php
if (isset($_POST['send']))
{
$fname = $_POST['firstName'];
if (!empty($fname))
{
echo "hello $fname";
} else {
echo "Please supply your first name.";
}
}
?>
$_POST['send'] is the name of your submit button, this will be the trigger for your PHP to initiate and run through the rest of the code.
$fname = $_POST['firstName']
This is just where I prefer to store the $_POST as a variable in the event you are going to re use it again it saves time writing the entire thing.
if(!empty)
if the username isn't empty (!empty meaning not empty) then perform the echo of $fname. however if it comes back as empty it will echo the else echo "please supply...;
Now for the form.
<form action="" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td><input type="submit" name="send"></td>
</tr>
</table>
</form>
Just a straight forward form with a blank action on mine (I prefer to keep the PHP within the same file however I normally relay it back to a Class within a different file.
Each form input (First Name / Submit) must have a name="" value otherwise the PHP cannot read it and run with it.
I hope this makes sense and isn't too puzzling :)
Your input field should be inside tag and method should be post. Like:
<html>
<body>
<Form method=post>
<input id=mytextfield name=mytextfield type=text />
<input type=submit value=Submit />
</Form>
</body>
</html>

How to stop the form input data from erasing after php validation invalid = true?

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>

How to use PHP for form validation?

Well, I have the following problem: my little test website is near completion and all that’s left is PHP validation on submit. But there exactly lies my problem. I can’t seem to let it validate when the user clicks submit.
I searched plenty of websites but on all of those they submit the page to the same page, and I submit the page to a new page. I don’t know how different this is from the first method but I can’t seem to get it to work.
I have 5 fields in my form which need to be required:
<table>
<tr>
<td align="right">Naam:</td>
<td align="left"><input type="text" name="naam" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Woonplaats:</td>
<td align="left"><input type="text" name="woonplaats" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Straatnaam:</td>
<td align="left"><input type="text" name="straatnaam" onkeydown="return names(event)"/></td>
</tr>
<tr>
<td align="right">Huisnummer:</td>
<td align="left"><input type="text" class="formnumbers" name="huisnummer"/></td>
</tr>
<tr>
<td align="right">Telefoonnummer:</td>
<td align="left"><input type="text" name="telefoonnummer" onkeydown="return phonenumber(event)"/></td>
</tr>
</table>
That’s all. My form action is as follows:
<form action="?page=pizza_bestelling" method="post" name="orderform">
I know PHP validation should be really easy (at least that’s what I’ve heard) but I can’t seem to work it out myself, so that’s why I decided to ask it here.
Now all it needs to do is check if one of those 5 fields is empty, if so don’t submit. Otherwise submit.
(Keep in mind that I have 16 fields in my form, it counts only for these 5 specific, the other 11 can be empty)
I appreciate any help in this matter, since it’s all that’s left before completing my website!
Thanks in advance!
Upon submiting you will lose "?page=pizza_bestelling" of the link, you can set it in a hidden input with that value if you need it passed.
set the method to method="post" in the form
and on the same page you will need something like
function validate_form($data)
{
//rules that will end with return false; if they are not valid
// example
if (!isset($data["naam"]) || $data["naam"] == '') return false; // if the name is not set or it's empty
// return true if all validation checks are passed
return true;
}
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$form_data['naam'] = $_POST['naam'];
$form_data['woonplaats'] = $_POST['woonplaats'];
// and so forth for each variable
// run the validate_form function for the data you got through POST
validate_form($form_data);
}else
{
//form displayed here
}
You want to set up an errors array which will store any errors, and allow you to print them out if necessary.
Then you check each variable in the following manner:
$errors = array(); //initialise error array
if (empty($_POST['naam'])) {
$errors[] = 'You forgot to add a name';
} else {
$name = trim($_POST['naam']);
}
This checks if the naam input and writes a message to the errors array if it's empty, or assigns the value to the $name variable if not.
Once you've gone through all your inputs, you can then perform a check on the errors array:
if (empty($errors)) { // If everything's OK.
//do what you need to do
} else {
echo '<p>The following errors occurred:<br/>';
foreach ($errors as $msg) {
echo "$msg<br/>\n";
}
echo '<p>Please try again</p>';
}
This only checks for empty fields of course - you should implement more validation for valid emails etc. For useability purposes you should really look at a one-page solution with sticky fields though.
Do a for each as follows:
$allowed = array("naam","woonplaats","stratnaam","formnumbers","telefoonnummer");
foreach ($allowed as $key => $val){
if($_POST[$key] == "")
$errors = true;
}
if($errors){
// don't submit
}
else {
// submit
}

AJAX .load() returns NULL

I'm building a website in PHP and I'm trying to implement asynchonous behaviour on some occasions, in this case to load an HTML form into an overlay and making it visible. This works as intended, however I'm now testing everything considering existing data.
So I basically created a variables.php file that sets values to the $_SESSION global and was working from there. Everything was working as expected on index.php, but as soon as I click the overlay I notice the values aren't passing through to populate the form that was added.
I already poked google for a few hours to no avail. I've added echo var_dump($_SESSION); on the index.php file and the values are all there. However on the overlay it returns NULL. I've even include_once("loginForm.php") right in the middle of index.php and that gave me the values. So there's something I'm missing in order to get the values to apply to .load() elements.
Here's some code:
variables.php
//added values to the $_SESSION global for testing purposes
$_SESSION['email'] = 'john#john.com';
$_SESSION['password'] = 'johnny';
$_SESSION['name'] = 'John';
$_SESSION['surname'] = 'Smith';
$_SESSION['country'] = 'UK';
$_SESSION['phoneOption'] = 'Mobile';
$_SESSION['phone'] = '987654321';
header-login.php
//this form accepts an email to check ifExists() and decide what's next
//the input #preLoginEmail assumes the value correctly
<form action="header-login.php" name="preLoginForm" id="preLoginForm" method="post">
<div id="login-part2">
<table id="preLoginTable">
<tr>
<td colspan="2">
<input type="text" id="preLoginEmail" title="Email" name="test-email" tabindex="1" size="10" maxlength="60" placeholder="Email" value="'. $email .'" />
</td>
</tr>
<tr>
<td><a title="forgotten password" href="header-login.php" id="preLoginForgot">forgot password?</a></td>
<td><input type="submit" class="btn1" name="preLoginRegisterButton" id="preLoginRegisterButton" tabindex="1" value="Login / Register" /></td>
</tr>
</table>
</div>
echo var_dump($_SESSION);//works
</form>
onClickEvents.js
//this call retrieves the HTML correctly although the variables dont get assigned to the input's value
$( "#preLoginForm" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
term = $form.find( "input[name='test-email']" ).val(),
url = $form.attr( "action" );
verifiedEmail = validateEmail(term);
if(verifiedEmail){
// Put the results in a div
$('#olContainer').load("../inc/loginForm.php");
overlayOn();
}
else {
$('.session-stat').css({ "background-color": "#A60000" });
}
});
loginForm.php
//when this form is loaded there are no values in the inputs and var_dump($_SESSION) returns NULL
<form id="loginForm" name="loginForm" method="post" action="booking.php">
//some blocks are static and created in plain html
<input name="email" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="<?php echo $email; ?>" />
//others are php variables to make the if/else statement more readable
$countryBlock ='<input name="agentuser" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="'. $country .'" />';
echo var_dump($_SESSION); //NULL
I kinda ran out of ways to figure out what's going wrong, and I just started learning about AJAX this week. If u need anything else just let me know in comments I'll try to be quick to edit. Thanks in advance.
#Fernando - I didn't know which way you decided to go, but if you have to use $_SESSION for this, include:
session_start();
at the beginning of each file you plan to use sessions on, before any content is rendered. Also, be careful to have a means for your users to overwrite their values, ie. with a post, so that once a value gets put in session, there is a way to change it and it doesn't keep overwriting the (new) value. I usually clear out my sessions on Page one of the form. You can do a
unset($_SESSION['test-email']);
...to unset the values. You can use a foreach loop here too.
A great site to compare the speed of loops in PHP is http://www.phpbench.com/ also.
Best of luck!

taking value from function in php and showing in div or column the value, reloading page with previous values

I am having two fields 'name' and 'username'. I am checking the username availability and this I am able to check. My problem is with the manner in which I display the form. I want to achieve
Showing messages in the same row in which the username is displayed but in the third column.
While showing the messages, it should display the previous entered values.
And I want to achieve this just with html, javascript and php. I don't want to go for any other language or technology
Login.php is building the form.
<?php
include 'login2.php';
function form($name, $username)
{
?>
<form name="mylogin" method="post">
<table>
<tr><td>Name</td>
<td><input type="text" id="name" name="name" value="<?php echo $name?>" required></td></tr>
<tr><td>Username</td>
<td><input type="text" id="user" name="user" value="<?php echo $username?>" required></td>
<td id="messgae"></td>//want to display message over here have tried value"<?php echo $message"?>
</tr>
<tr><td><input type="submit" name="submit" value="Username Availability Check"></td></tr>
<?php usercheck()?>
</table>
</form>
<?php
}
?>
<?php
form('','')
?>
In Login2.php I am just checking the username and right now I am not inserting the values, so that the insert query is commented and for sending back the entered values by user. The problem I am facing is, the form is getting displayed twice after I click submit button or user availability check button. I know it is happening because I am calling the function twice but how to avoid it?
Code
<?php
function connect()
{
mysql_connect('localhost','root','password');
mysql_select_db('loginprac');
}
function usercheck()
{
if(isset($_POST['submit']))
{
connect();
$name=$_POST['name'];
$user = mysql_real_escape_string($_POST['user']);
$check_for_username = mysql_query("SELECT user from userpage WHERE user = '$user'");
$count = mysql_num_rows($check_for_username);
if($count != 0)
{
form($name,$user);
}
}
}
/*function insert()
{
connect();
if(isset($_POST['submit']))
{
usercheck();
$name=$_POST['name'];
$user=$_POST['user'];
$sql1= "INSERT INTO userpage (name,user) VALUES ('$name','$user')";
mysql_query($sql1);
}
}*/
?>
Get the <form> outside the function form(). Pass only the messages and username to the function.
If you want to use javascript,
on clicking submit button/useravailability check button, call an ajax function which can then go to your php code with the newly entered username(to check the availaility).
Check the availabilty and
print your message there.
Then replace html content(with the ajax response text) in your document where you actually want the message.
here an introduction to such an ajax function
or try jquery ajax

Categories