Same page processing - php

How can process a form on the same page vs using a separate process page. Right now for signups, comment submissions, etc I use a second page that verifies data and then submits and routes back to home.php. How can I make it so that on submit, the page itself verifies rather than using a second page.

You can tell the form to submit to the PHP's self, then check the $_POST variables for form processing. This method is very good for error checking as you can set an error and then have the form reload with any information the user's previously submitted still in tact (i.e. they don't lose their submission).
When the "submit" button is clicked, it will POST the information to the same page, running the PHP code at the top. If an error occurs (based on your checks), the form will reload for the user with the errors displayed and any information the user supplied still in the fields. If an error doesn't occur, you will display a confirmation page instead of the form.
<?php
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['yourname']) {
$error['yourname'] = "<p>Please supply your name.</p>\n";
}
if(!$_POST['address']) {
$error['address'] = "<p>Please supply your address.</p>\n";
}
//No errors, process
if(!is_array($error)) {
//Process your form
//Display confirmation page
echo "<p>Thank you for your submission.</p>\n";
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
}
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<?=$error['yourname']?>
<p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
<?=$error['address']?>
<p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>

The easiest construction is to detect whether the $_POST array is not empty
if(isset($_POST['myVarInTheForm'])) {
// Process the form
}
// do the regular job

you can check if it was POST request inside the page's code and then check the data. If it was GET request - just show the form.
But please remember that is is a good practice to show successfull form submission results on a different page served through GET request, i.e. any successfull form POST should be answered with redirect to the success page.

You could of course explore looking into AJAX requests, where you would make an asynchronous call to your handler script, and then update then update the sending page with a success message. This gives the impression of "Same page processing" i.e. The page doesn't have to refresh.
It really depends on the effect you are trying to achieve however.

#Michael Irigoyen: It works fine, but on first rn/load, it shows:
"Notice: Undefined variable: error in C:\xampp\htdocs\same_page.php on line 28"
How to handle this notice?
Got it now:
"Used isset, # etc. to supress errors..."
"Works like a charm!!!"
"Now i'll try it on my code..."

I have saved a thank you message and refreshed using session variables.
if(!is_array($error)){
$_SESSION['message'] = 'Thank You!';
header('Location: yourpage.php');
exit();
}
and then use this in the top of the form:
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
unset($_SESSION['message'];
}
This should refresh the page and show the message and then if they refresh the page the session variable is empty so the thank you won't show. This is called a flash message.

Related

How to avoid the alert after the first time loading the page

I want to check if the form was filled out correctly but the alert appears after I load the page. I guess a site refresh is submitting the login button.
I try to check the incoming data and if they are wrong, it should show an alert.
<?php
$alert = "";
if ($_POST['username'] == null || $_POST['password'] == null){
$alert = "Please fill in all fields!";
}
if ($alert){
echo $alert;
}
?>
<form method="POST" action=""> <!-- reloads this page -->
<input type="text" name="username"/>
<input type="password" name="password"/>
<button type="submit" name="login">Login</button>
</form>
If I open the page, the alert appears instantly. How should I do the check, that the alert does not appear after the first load.
I hate to suggest javascript as the solution, but in this case, javascript is the best solution.
With javascript, you can interrupt the form submission process - do some stuff (such as validate the form fields) and then either return false (cancels the submit) or do nothing (the form submission will continue). But Barmar is straight-on correct with his explanation of what is happening. (Of course he is: it's Barmar )
So the overview is:
Use $('#yourFormID').submit(function(){}) to trap the form submission process
Inside that function, perform your field validation
If a field fails validation, display a message and return control to the user
If all fields validate okay, do nothing else - the form will finish submitting as if there was no interruption at all.
Here is another question/answer that demonstrates how to do that.
How to direct a user directly to a form
The IF-Statement is fine, so your problem is in your Session or Cache.
You can destroy your Session, if you close your browser, but this maybe need some time to destroy the session, so you could delete cache, cookies, etc in your browser setting.
But you can also use session_destroy(); in php to destroy all Variables of POST or GET.

How to run a php code, only if the "submit" button redirect you.

This is my admin panel code:
<form action="connectdb.php" method="post">
<input type="text" name="name">
<input type="submit">
</form>
So, It so, the code in connectdb.php will only run, if the "submit" button redirects a user to it. It will not run, if a user directly open /connectdb.php page.
Do I need to start some session, something like that?
Note: I am a newbie, so please explain in detail.
Since your form is using method="post"you can place the following code at the very beginning of your connectdb.php file:
<?php
if (empty($_POST)){
exit;
}
//The rest of your code goes here
This checks to see if the $_POST variable either does not exist or does exist but is empty. If this returns true that means your form was not submitted and a user went to the page directly. The script will then exit and a blank screen will be displayed.
Instead of displaying a blank screen, you may instead want to redirect to a different page such as this:
<?php
if (empty($_POST)){
header("Location: index.html");
exit;
}
//The rest of your code goes here
Whenever you do a redirect like this, it is important to place an exit; statement directly after it, otherwise your script could still process some of the other statements and send data to the browser that shouldn't be sent. This of course could be a security risk in some cases. An exit statement prevents this kind of security risk.
Not sure if you really need it, but you can add a name attribute like the following:
<input name="submit_button" type="submit">
So when you click this button a $_POST['submit_button'] variable will be created on the PHP side, and then you can use it to check if the button was clicked:
if(isset($_POST['submit_button'])){
// your code
}
<input type="submit" name="submit_btn">
Now in your connectdb.php check,
<?php
if(isset($_POST['submit_btn']))
{
//do your code
}
else
{
//redirect to your home page
}
?>

Object Oriented PHP to pass message to user upon success of function

I am new to OO php so this may seem basic..
Basically I have a list of courses a user can book. I have got it so the user can remove the course from their list, but I want a message to be displayed to them after they delete. I have done something similar to what I want here:
<form name="removecourse" action="<?php bloginfo('url');?>/user/<?php echo $current_user->first_name ; ?>" method="post">
<input type="hidden" value="<?php the_id();?>" name="courseid" />
<input id="removebutton" type="submit" name="removecourse" value="Remove">
</form>
The form sends the required data to the same page, and at the top of that page is a check to see if the forms post name is present in $_POST[] like so:
if(isset($_POST['removecourse']) && !empty($_POST['removecourse'])){
$courseManager->delete_post($_POST['courseid'], $_POST['cancel-reason']);
echo $courseManager->delete_response;
};
This is where the Class and object part comes in...
public $delete_response;
function delete_post($postid, $reason){
//stuff to actually delete the post
$this->delete_response = 'Thanks, your course has been removed.';
}
So here I am adding a value to the delete_response variable and calling it above at the top of the page. This works, but when I refresh the page the message is still there as I am resubmitting the POST. I am just wondering if what I am doing is along the right track, and how to implement a Post/Redirect/Get type functionallity to stop the messaage from appearing on page refresh?
You have to check, either your course has been already deleted, is it simple as that :).
Yours displaying it again because:
if(isset($_POST['removecourse']) && !empty($_POST['removecourse'])){
//is always true when posted again.
}
You have to check the existiance

PHP form validation error messages placement

Is it possible to place error messages resulted from form validation inside the form, using PHP/XHTML/CSS only?
You can put error messages anywhere on the site you wanted. It all depends on where in your scripts you place your code to emit it.
One strategy I've seen used a lot in PHP Frameworks when AJAXy submissions are disabled is to have a field to display the error on the page, and then actually populate that field with the data if the page comes back with an error.
Such as:
<label for="field">Label"><input name="field" type="text" />
<?php if($_POST['errors_field']) echo '<p class="error">'.$errors['field'].'</p>'; ?>
This strategy would only show the <p> tag when the page input box has an error. This method of course involves returning a populated array of all errors to the page when it fails validation.
I would make 2 pages one with the form like this. We will call it form.php. Make sure your form method is "post", and you have named your inputs. create a div that will be used for error callback($error). You can place the Error var anywhere you want not just in the form.
<form method="post">
<input type="text" name="text">
<div><?php echo $error ?></div>
<input type="submit" name="submit">
</form>
Next Make another php page like this and include the form.php page at the bottom. set error as empty string first. See if the button is clicked(isset). If the field is equal to a empty string set the error($error). if no error Process the form. Hope this helps.
<?php
$error = '';
if(isset($_POST['submit'])){
if($_POST['text'] == ''){
$error = "Here is your Error inside the form.";
} else {//"Sanitize and Process the Form";
}}
include 'form.php';
?>

pass value from page to another in PHP

I am sending login status = fail, back to my login page.Here is my code-
header("location:index.php?login=fail");
but that is sending through URL like-
http://localhost/303/index.php?login=fail
is there any way to pass value without showing in URL? And how to get this value on the second page?
You are passing that value via a GET request, which is why it appears in the URL. In order to pass a value without showing it in the URL, you want to pass it via a POST request.
In order to do this you aren't going to want to "return" the value to your login page. Instead, whatever php form is handling the process of logging in the user after they click the "login" button, will decide what to show the user.
In PHP post variables can be accessed by the global $_POST object -
$_POST['username'];
Would get the value with the name "username" that you passed via POST:
<form method="post" action="checkLogin.php">
Username:
<input type="text" name="username" maxlength="25" />
Password:
</td><td><input type="password" name="password" />
<input type="submit" name="submit" value="Login">
</form>
In order to dynamically save and show errors to the user, you can store them in the session, for example have a file called "errors.php"
<?php
if (isset($_SESSION['errors']))
{
echo $_SESSION['errors'];
}
unset($_SESSION['errors'])
?>
And in your php that checks the login, do:
session_start();
$_SESSION['errors'] = "Invalid username or password.";
Then redirect to your login page (don't pass any variables) and on your form always have this field:
<?php include("errors.php"); ?>
If you didn't have any errors, it won't show anything and the login page will look normal.
Note: In any php form that you use a session_start(), it HAS TO BE THE FIRST THING in the form.
Other ways are to use session or hidden fields but you what you are doing is fine for the purpose. You can later retrieve the value like this:
if ($_GET['login'] === 'fail')
{
// failed.......
}
there are several ways to accomplish your task
Modern AJAX way. Form being sent using AJAX. No page reload until password is correct. Errors shown in place. Requres javascript.
Post/Redirect/Get pattern. Form being sent using regular POST. No redirect on errors, shown in place.
sessions, when we store an error in the session

Categories