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

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

Related

html checkbox onChange methode in php

Here is my problem, I know only html and php and I have no clue about how to use javascript... And all the solutions about my problems seems to be resolved in javascript and I wondered if there was a way to do it with php so that I could understand what I do.
I want to put a checkbox on the corner of my page (for instance "hide information") that would refresh the page automatically when checked and that would hide information on the page.
What I currently do is :
<?php
if(isset($_GET['condition']))
$_SESSION['condition'] = true;
else
$_SESSION['condition'] = false;
?>
...
...
<form>
<input type="checkbox" name="hide" value="1" onChange="this.form.submit()" <?php if($_SESSION['hide']) echo "checked";?> > hide information
</form>
I am facing two problems :
the first one is that I want the checkbox to stay checked/unchecked when the page is refreshed.. I solve that poorly with my php code, but there surely exists something better to do that.
When the box is checked, the page is refresh with only "hide=1" as an url argument, but I would love to keep all the other arguments that were there before the page was refreshed. Is there a way to refresh the page and keep all the arguments while knowing that the box is checked/unchecked ?
thanks for your help, and sorry for my poor knowledge.
Regarding the second point of your question you can move the POST (or GET) array to the SESSION one and back with the following code:
if(isset($_POST) & count($_POST)) { $_SESSION['post'] = $_POST; }
if(isset($_SESSION['post']) && count($_SESSION['post'])) { $_POST = $_SESSION['post']; }
I use this to do exactly the same. When I reload the page I keep the posted values.
Regarding the first point you are already on the right path.
I don't see anything wrong with how you've tried to solve problem 1.
Regarding the URL problem 2, either put session_start(); at the top of the page to get the session to work correctly.
Alternatively have hidden inputs in this pages' form and echo out the previous pages' POST values.
<form action="" method="post">
<input type="hidden" name="condition" value="<?php echo $_POST['condition']; ?>" />
<!-- have hidden inputs from previous page here, plus your checkbox to retain post values from the previous page -->
</form>
Although I'd recommend POST for this, you can do GET although it gets a bit messy like so:
<form action="thispage.php?condition=<?php echo $_GET['condition'];?>" />

Sending value from a form to a html tag counter

I am looking for a bit of code to do the following:
A form containing a single text field and a submit button, must send the value of the text field to a landing page that automatically counts how many html tags that this page contains.
E.g. if the text field states stackoverflow.com, the landing page should say (H1 tags = 20) with many more parameters to come.
How is this done? I know how to make a form, but I do not know how to make it send its value to the landing page.
<form action="landingpage.php/" method="post">
The URL
<input type="text" name="cf_name">
<input type="submit" value="Submit">
</form>
This piece of code is a perfect answer to your question.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">
Type In Something: <input name="random-info" type="text" size="25">
<input type="submit" value="Submit">
</form> <br>
<?php
echo "You Typed: " . $_GET['random-info'];
?>
you get the method into the url, then you can use them on another page.
To access data from a form it depends on the method. Since your code shows a post message you simply access it in the php on the landing page by user $POST_['cf_name'].
To learn more you can check out:
http://w3schools.com/php/php_post.asp about the post method and http://w3schools.com/php/php_get.asp about the get method.
Also an invaluable source is php manual itself.
As far as counting the tags, not really sure what you are trying to achieve.
If you are counting the tags in the page you create, just make a variable and add to it each time you put that specific tag on the page.
Then you can put those values in a hidden field of the form to be passed into your landing page.

I can't use GET and POST at the same time in PHP

Near the top of my page, I have this:
<?php $id = $_GET['id']; ?>
Then I have some form check conditionals that read from POST:
if (isset($_POST['completeSubmit'])) {
//code
}
And finally, I have an HTML form which looks like this:
<form action="<?php echo $_SERVER['PHP_SELF']."?id=$id"; ?>" name="complete" method="post">
<input type="submit" id="textButton" name="completeSubmit" value="[mark as complete]">
</form>
The page is initially accessed by using GET with an id variable like this:
http://website.com/page.php?id=1
All subsequent form submissions (which get redirected to the same page) fail. I know you can't send both GET and POST in the same request, but seeing as my form is submitting to $_SERVER['PHP_SELF']."?id=$id" using POST shouldn't it work? This is my first time trying this so it is quite possible I've overlooked something trivial.
You can use get and post at the same time, but you shouldn't. If you want to continue to send the ID this is as simple as:
<form ...
<input type="submit" ...
<input type="hidden" name="id"
value="<?php echo htmlspecialchars($_GET['id'], ENT_QUOTES); ?>" />
</form>
Of course you can not use GET and POST methods simultaneously.
However you can use a query string while sending a form using POST method, which being used to populate $_GET array.
To find a certain error you have to provide more info. At least 2 things:
how does HTML form look
what do yo see in the query string after posting the form.
and errr...
do you use any header redirects in the form processing?

Same page processing

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.

PHP Form Processor Error Passback

I have a basic PHP form page that contains quite a large amount of data that will be saved into about 4-5 different tables in MySql once it is all done. Since constructing this save routine will take a bit of PHP I'm looking to have the POST action to not point at PHP_SELF and instead a separate PHP file for processing.
Where all general data such as phone numbers, email, zip codes, etc. will be validated prior to the submit is passed to the processor script, if an error is returned by the processor...
What is the best practice way to point back to the original form page (HTTP_REFERER) while maintaining data input?
Form page:
<form action="processor.php" action="post">
<!-- lots of fields -->
<input type="submit" id="submitButton" name="Save" value="Save" />
</form>
Processor page:
<?php
if ( isset($_POST['date']) && ($_SERVER['HTTP_REFERER'] == "form.php") )
{
$errors = false;
//attempt to put data in database
if ( $errors )
{
//Pass back to the form.php page with error message and all data intact
}
}
?>
I have come across this problem before, how we solved this was to put all the fields into a session, then redirect back to form.php using header("Location: form.php");
When the data was posted to the form, we stored the $_REQUEST into a $_SESSION['post']; if the validation failed, we sent it back to the form, populated the fields and unset the session.
So for example
$_SESSION['post']['field_a'] = $_REQUEST['field_a'];
$_SESSION['post']['field_b'] = $_REQUEST['field_b'];
With some fancy naming conventions you can just loop this to make it easy.
Then on the Form page, we just checked to see if there was some data, or just echo the data regardless.
$str_field_a = #$_SESSION['post']['field_a'];
...
<input name="field_a" value="<?php echo $str_field_a; ?>" />
...
unset($_SESSION['post']);
This is probably a messy way of doing this, but it has proven effective for our purposes. Just thought I'd share.
I would send a post back to form.php containing errors and values. I use the same method in my personal project.
if ( $errors ) {
?><form action="form.php" method="post" name="error">
<input type="hidden" name="errcode" value="<?php echo $errorcodes; /*or whatever message*/ ?>" />
<input type="hidden" name="anotherdata" value="anothervalue" />
<?php /*you can add all post datas here as hidden field*/ ?>
</form>
<script type="text/javascript">document.error.submit();</script><?php
}
And this is similar to my form.php
//first I set default blank variables for form
$formvalue="";
$formnumericvalue="";
//i set them, yay!
//if I get values from post.php, I update the values
if (isset($_POST['iserror'])) { //you can either echo a error message or update current data here, I'm showing this for both
$formvalue=$_POST['formvalue'];//don't forget to validate these!
$formnumericvalue=$_POST['formnumericvalue']; //don't forget to validate these!
}
//I also do this method for edit forms
//and finally I show the form
?>
<form name="form" method="post" action="post.php">
<input type="text" name="formvalue" value="<?php echo $formvalue; ?>" />
</form>
I think you can do that using an array of error.
Set error flag false (if error occurs then set it true and so not store in database).
Check element 1, if error then store it in array $error['name'] = 'value'
Similarly check all elements, and store using same procedure.
In the end if error flag is set to false do not store in database and (if on the same page, you will be able to access the array on form where you want to display error message. )
if(isset($error['elementname'])) echo $error['elementname'];
below the page.
However, the best approach is to use an Object Oriented approach.
[UPDATE]
storing php objects on html form element and passing php objects through GET method?
how to send redirect page pass variables as post variables from a php script
Also I guess, storing the whole object in SESSION would not be a bad approach

Categories