php get results on same page - php

I Have a php form page where users fill the data and process page to add data to database, Its working fine, But problem is I need the results from process page to be displayed back on to my main page? How to get results back to main page?

In the form's action attribute, set the path to $_SERVER['PHP_SELF'] rather than processing file. This way, form will submit to same page where you can process it.
<form action="<?php echo $_SERVER['PHP_SELF'];?>">
.....
</form>

How about
<form action="mainPage.php" ...>
Simple and your Data will be on the main page.

Use sessions. In script assign a error message to session variable and do redirect. On script.php
$_SESSION['error'] = 'Incorrect email';
index.php
echo $_SESSION['error'];
Don't forget session_start() in begin of scripts.

There's a wide variety of ways, depending on what you're talking about. You'll likely want to use session variables, though. In the processing script:
<?php
start_session();
// Do your processing here
$_SESSION['myvar'] = $finished_data;
?>
And in the main page that called it:
<?php
session_start();
if(!empty($_SESSION['myvar'])) {
$data = $_SESSION['myvar'];
}
// Use $data here as you need
?>

Looks to me like you need to include some Javascript here, then post the returned data to wherever you want. there is.. post to same pagewith...document.getElementById('yourDiv').innerHTML = 'yourReturnedData';
or with $_GET variables.
example...
yoursite.com/yourPage.php?data1=data1&data2=data2
Get returned data by ...
$var1 = $_GET['data1'];
$var2 = $_GET['data2'];
Hope this is of use

Related

How do i go about echoing back to a form from a form post action?

I have a form containing a textarea for inputing text into. The form also contains a submit button. After pressing the submit button it posts the text within the textarea into my php document. Within my php document the text is added to a database. Once it has been added to the database I would like it to echo back a response telling the user that it has added the text to the database successfully.
However, if i make it echo that response back to the home page, there is nowhere declared for it to display the echoed message. Has anyone got an idea of what i should be doing in order to get this working? Many Thanks.
Normally i wouldn't use a post straight from the form and i would use ajax and then display the data within a paragraph or something on it's return, however since the form is doing the post it's self i am not sure where to then declare where the response should show up.
The bellow displays my html form code and shows it's action to post to a php file.
<div id="userban2"><form id="bannable" action="/onlineusers.php" method="post"><p> Type username to ban bellow:</p>
<textarea name="banned" id="banned" maxlength="255"></textarea><br/>
<input type="submit" value="Send" class="extrabuttons" onclick="return false; preventDefault();">
<div id="cancelban" class="extrabuttons"><p> cancel</p></div>
</form>
However when in my php file i write ....
echo "the information has been added to the database successfully";
It might send the echo back however it isn't declared to display anywhere how can i change this to make it display the response within my form?
As requested return from my php
if(isset($_POST["banned"])){
$ban_name = $_POST["banned"];
bannedd($ban_name);
}
function bannedd($ban_name) {
$query1 = mysql_query("INSERT INTO banned_users (username,firstname,lastname,email,password,ip_address,sign_up_date,last_logged_in,about,sta rr,userpref) VALUES('$usernameb','$fnameb','$lnameb','$emailb','$passwordb','$ip_addressb','$sign_up_date b','$last_logged_inb','$aboutb','$starrb','$userprefb')") or die("Could not insert your informaion");
echo "This user has successfully been banned";
}
The form posts what is written in the form due to it having the action and method of post to my php. However should i then have any return i am not sure how i declare where the returned information should then show (The echoed message).
If I understand you correctly, your form is in some index.php file and sends the data to other file - onlineusers.php, and you want to display the message in the original page?
If this is the case, the most simple way I can think of is redirect back to the original page with a URL parameter, instead of echoing.
Do this at the end of onlineusers.php:
<?php
// insert text into DB ...
header("Location: index.php?result=ok");
?>
This redirects the browser back to the original page with the form. There you check if the status variable is set:
<html>
<head></head>
<body>
<?php if(isset($_GET["result"]) && $_GET["result"]=="ok") { ?>
<p>The information has been added to the database successfully</p>
<?php } ?>
<form> ... </form>
</body>
</html>
As you can probably see, you could set other results, such as "error" this way.
If you don't like the extra string in your URL, then create a cookie after processing the form in onlineusers.php and back at the original page, check if such cookie has been set. If you need more detail on that, let me know. And if you're asking something completely different, well, never mind :)
Your form is being submitted to /onlineusers.php
This is where you would want to add your echo statement.
If you require the info on the same page you technically return to the same page with the form action being $_SERVER['PHP_SELF'].
<form id="bannable" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Then you can put in a conditional statement prior to the load of your document, and include the PHP script.
<?php
$testVar = false;
$msg = '';
if($_POST) {
include '/onlineusers.php';
//... do something e.g post to database and return true.
}
if($testVar) {
$msg = 'Successful writing to DB!';
} ?>
<html>
<body>
<?php echo $msg; ?>
</body>
</html>
This will check to see if you have any post data, if you do, then it includes the script you specify. Maybe set $testVar to true if the writing to DB is successful, and then return $msg in your HTML.

PHP form stays at form action

I have an HTML form with a form action of foo.php. However, when I click the submit button, I get redirected to the "foo.php", but I don't get redirected back to the page where the form is located. Could anyone tell me if there is some sort of code that is necessary for this to happen?
Here's my PHP file, if this helps:
<?php
$title = $_POST['title'];
$content = $_POST['content'];
$postid = $_POST['postid'];
?>
You can set header redirect back to form file, after processing the form data. Assuming your form file has name "form.php"
header('location: form.php');
Two ways:
<?php
header('Location: myform.php');
?>
or use javascript:
<script>
window.location('myform.php');
It very simple. Try to understand your task first. You need to redirect to another page after completing your task whatever save/update/processing data.
just set header in your php script after completing your work.
<?php
// your all code will goes here
header("Location: myform.php");
?>

header(location) on form does not work after submit button clicked

This is my code for my submit button. Once data submitted to mysql i want it to redirect to page.html.
<form name="gender."; action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
I have added
<?php
header("location:page.html");
exit; }
<?
to the very top of my form page. However it just loads page.html rather loading after submit button is clicked.
1) Please don't use PHP_SELF, it is vulnerable to exploitation. If you want the action to be the same page, just leave it empty.
2) The header(), which I assume is at the top of the page since it works, has no control on it.
EDIT1: Expanding based on question in comment below.
3) The header() directive will forward the browser to the new page and stop any further processing. Because of this, all the MySQL processing should be complete before redirecting.
4) The $_POST array gets the key names from the name attribute of the inputs, so be sure that your <input type="submit" name="submitbtn" ... matches the $_POST['submitbtn']
<?php
if(isset($_POST['submit'])){
// MySQL stuff goes here
header("Location: page.html");
exit;
}
?>
you'll have to add the condition before header to check if data is submitted or not.
eg:
if(isset($_POST['btnname'])
{header("location:page.html");
exit; // this is unnecessary
}
Also, if you want to use form for submission, you'll need to post it on page.php.
as this code will redirect the page without saving the form's data anywhere.
My main suspect is that your PHP is set up to suppress warnings and errors. Turn them on in the php.ini file and see what the message is.
Most likely it will say something along the line like "html headers cannot be sent as there is already output in line so and so..."
The PHP hear function cannot work if there is any output already echoed from the page.
<?php
ob_start();
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['button'])){
header('Location:page.html');
exit;
}
?>
Can you modify the code like this ?

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

When I press the 'refresh' button on my browser, it seems that $_POST variable is preserved across the refresh.
If I want to delete the contents of $_POST what should I do? Using unset for the fields of $_POST did not help.
Help? Thanks!
The request header contains some POST data. No matter what you do, when you reload the page, the rquest would be sent again.
The simple solution is to redirect to a new (if not the same) page. This pattern is very common in web applications, and is called Post/Redirect/Get. It's typical for all forms to do a POST, then if successful, you should do a redirect.
Try as much as possible to always separate (in different files) your view script (html mostly) from your controller script (business logic and stuff). In this way, you would always post data to a seperate controller script and then redirect back to a view script which when rendered, will contain no POST data in the request header.
To prevent users from refreshing the page or pressing the back button and resubmitting the form I use the following neat little trick.
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// This code can be used anywhere you redirect your user to using the header("Location: ...")
if (array_key_exists('postdata', $_SESSION)) {
// Handle your submitted form here using the $_SESSION['postdata'] instead of $_POST
// After using the postdata, don't forget to unset/clear it
unset($_SESSION['postdata']);
}
?>
The POST data is now in a session and users can refresh however much they want. It will no longer have effect on your code.
Use case/example
<!-- Demo after submitting -->
<?php if (array_key_exists('postdata', $_SESSION)): ?>
The name you entered was <?= $_SESSION['postdata']['name']; ?>.
<!-- As specified above, clear the postdata from the session -->
<?php unset($_SESSION['postdata']); ?>
<?php endif; ?>
<!-- Demo form -->
<?php if (!isset($_SESSION['postdata'])): ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name" /><br />
<input type="submit" value="Submit" />
</form>
<?php endif; ?>
Simple PHP solution to this:
if (isset($_POST['aaa'])){
echo '
<script type="text/javascript">
location.reload();
</script>';
}
As the page is reloaded it will update on screen the new data and clear the $_POST
;)
this is a common question here.
Here's a link to a similar question. You can see my answer there.
Why POST['submit'] is set when I reload?
The basic answer is to look into post/redirect/get, but since it is easier to see by example, just check the link above.
My usual technique for this is:
<?php
if ($_POST) {
$errors = validate_post($_POST);
if ($!errors) {
take_action($_POST);
// This is it (you may want to pass some additional parameters to generate visual feedback later):
header('Location: ?');
exit;
}
}
?>
How about using $_POST = array(), which nullifies the data. The browser will still ask to reload, but there will be no data in the $_POST superglobal.
$_POST should only get populated on POST requests. The browser usually sends GET requests. If you reached a page via POST it usually asks you if it should resend the POST data when you hit refresh. What it does is simply that - sending the POST data again. To PHP that looks like a different request although it semantically contains the same data.
This will remove the annoying confirm submission on refresh, the code is self-explanatory:
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER[REQUEST_URI]);
exit;
}
if (#$_SESSION['postdata']){
$_POST=$_SESSION['postdata'];
unset($_SESSION['postdata']);
}
You can't, this is treated by the browser, not by any programming language. You can use AJAX to make the request or redirect the user to the same (or another) page.
The "best" way to do this is Post / Redirect / Get
http://en.wikipedia.org/wiki/Post/Redirect/Get
After the post send a 302 header pointing to the success page
I had this problem in an online fabric store, where there was a button to order a fabric sample on the product page, if a customer had first ordered a product and then wanted to order a sample of a different colour their previous order would be duplicated, since they never left the page and the POST data was still present.
The only way I could do this reliably was to add a redirecting page (or in my case in WordPress, add action to "parse_request" for a mock url), that redirects back to the referring page.
Javascript:
window.location.href = '/hard-reset-form';
PHP:
header('Location: ' . $_SERVER['HTTP_REFERER']);
die();
This way you are coming back to a new page, all POST data cleared.
Set an intermediate page where you change $_POST variables into $_SESSION. In your actual page, unset them after usage.
You may pass also the initial page URL to set the browser back button.
I have a single form and display where I "add / delete / edit / insert / move" data records using one form and one submit button. What I do first is to check to see if the $_post is set, if not, set it to nothing. then I run through the rest of the code,
then on the actual $_post's
I use switches and if / else's based on the data entered and with error checking for each data part required for which function is being used.
After it does whatever to the data, I run a function to clear all the $_post data for each section.
you can hit refresh till your blue in the face it won't do anything but refresh the page and display.
So you just need to think logically and make it idiot proof for your users...
try
unset($_POST);
unset($_REQUEST);
header('Location: ...');
it worked for me
I can see this is an old thread, just thought I'd give my 2cents. Not sure if it would fit every scenario, but this is the method I've been successfully using for a number of years:
session_start();
if($_POST == $_SESSION['oldPOST']) $_POST = array(); else $_SESSION['oldPOST'] = $_POST;
Doesn't really delete POST-ed values from the browser, but as far as your php script below these lines is concerned, there is no more POST variables.
This is the most simple way you can do it since you can't clear $_POST data by refreshing the page but by leaving the page and coming back to it again.
This will be on the page you would want to clear $_POST data.
<a class="btn" href="clear_reload.php"> Clear</a> // button to 'clear' data
Now create clear_reload.php.
clear_reload.php:
<?php
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
The "clear" button will direct you to this clear_reload.php page, which will redirect you back to the same page you were at.
If somehow, the problem has to do with multiple insertions to your database "on refresh". Check my answer here Unset post variables after form submission. It should help.
The Post data can be clear with some tricks.
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST); //unsetting $_POST Array
header("Location: ".$_SERVER['REQUEST_URI']);//This will let your uri parameters to still exist
exit;
}
?>
In my case I have used the below trick to redirect user to the same page once the $_POST operation has been done.
Example:
if(!empty($_POST['message'])) {
// do your operation here
header('Location: '.$_SERVER['PHP_SELF']);
}
It is a very simple trick where we are reloading the page without post variable.
I see this have been answered. However, I ran into the same issue and fixed it by adding the following to the header of the php script.
header("Pragma: no-cache");
Post/Redirect/Get is a good practice no doubt. But even without that, the above should fix the issue.
I had a form on my account page which sent data with POST method and I had to store the received data in a database. The data from the database was supposed to be displayed on the webpage but I had to refresh the page after the POST request to display the contents in database. To solve this issue I wrote the following code on account page:
if (isset($_POST['variable'])){
echo '
<script type="text/javascript">
location.href="./index.php?result=success";
</script>';
}
Then on index.php I refreshed the page and sent the user back to my account page as follows:
if (isset($_GET['result'])) {
echo'<script>
//reloads the page
location.reload();
//send user back to account.php
location.href="./account.php"
</script>'
}
You should add the no cache directive to your header:
<?php
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
?>
This works for me:
<?if(isset($_POST['oldPost'])):?>
<form method="post" id="resetPost"></form>
<script>$("#resetPost").submit()</script>
<?endif?>

Avoiding form resubmit in php when pressing f5

I have the following code on my site (using php and smarty) to try and avoid a form resubmitting when I hit f5:
if ($this->bln_added == false) {
if (isset($_POST['submit'])) {
$this->obj_site->obj_smarty->assign('title', $_POST['tas_heading']);
$this->obj_site->obj_smarty->assign('desc', $_POST['tas_description']);
}
} else {
$this->obj_site->obj_smarty->assign('title', '');
$this->obj_site->obj_smarty->assign('desc', '');
unset($_POST);
}
bln_added is false by default, but changes to true once the form is successfully submitted. The smarty variables title and desc are used in the template to keep the form content there in case there is a user error and they need to change what they entered.
If the form is submitted successfully it sets bln_added = true, so the second bit of code should not only clear the form fields, but also empty $_POST. But if I press f5 the post data is still there.
Any ideas?
Your method could work in theory, but there's a much easier way.
After submitting the form successfully, perform a redirect. It doesn't matter where to, but it'll clear the $_POST.
header('Location: http://www.example.com/form.php');
In your case, it sounds like you want to redirect to the page you're already on. Append a $_GET parameter to the URL if you want to display a confirmation message.
Hope this helps,
Tom
The solution is a pattern commonly known as Post/Redirect/Get
The best way to handle forms is to use self-submission and a redirect. Something like this:
if (isset($_POST)) {
// Perform your validation and whatever it is you wanted to do
// Perform your redirect
}
// If we get here they didn't submit the form - display it to them.
Using the CodeIgniter framework:
function index() {
$this->load->library('validation');
// Your validation rules
if ($this->form_validation->run()) {
// Perform your database changes via your model
redirect('');
return;
}
// The form didn't validate (or the user hasn't submitted)
$this->load->view('yourview');
}
You can rewrite your form-submit into AJAX-way. If you need to show HTML-content, return it in JSON-format and insert with JavaScript(jQuery for example.)
I solved this (in php) by:
in the form add a unique identifier (id+counter) not based on time() (!!!)
post to a separate file (postform.php) that checked for a session with that unique identifier
a) if session with unique identifier was NOT found: post to the database and fill session with unique identifier
b) if session with unique identifier was found: do nothing
after either 3a/3b redirect to result page with header('Location: http://mydomain.com/mypage')
Result is:
no resubmit actions on either refresh/backbutton and only resubmit warning on double click backbutton (but no resubmit action)
Use Header location after successful post action
header('Location: '.$_SERVER['HTTP_REFERER']);
It works for me if I use either header() or exit() at the end of my code, for example, after I save some data.
The best method I found is using javascript and css. Common php redirection method header('Location: http://www.yourdomain.com/url); will work but It cause warning " Warning: Cannot modify header information - headers already sent" in different frameworks and cms like wordpress, drupal etc. So my suggestion is to follow the below code
echo '<style>body{display:none;}</style>';
echo '<script>window.location.href = "http://www.siteurl.com/mysuccesspage";</script>';
exit;
The style tag is important otherwise the user may feel like page loaded twice. If we use style tag with body display none and then refresh the page , then the user experience will be like same as php header('Location: ....);
I hope this will help :)
the answer you are looking for is this magic one liner:
header('Location: '.$_SERVER['HTTP_REFERER']);
e.g
if(isset['submit']){
//insert database
header('Location: '.$_SERVER['HTTP_REFERER']);
}
Header redirect after post is necessary, but insufficient.
In PHP side after submitting the form successfully, perform a redirect. Eg. header('Location: http://www.example.com/form.php');
But it is not enough. Some users press links twice (doubleclick). A JavaScript is required that would disable submit button after first click.
Try my own one, maybe it isn't best solution (done quickly), but I've test it and it works. Tested on Chrome. Click to see how it looks BR
<?php
session_start(); // Start session
?>
<html>
<head>
<title>
Test
</title>
</head>
<body>
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
<?php
if(isset($_POST['submit']))
{
$_SESSION['name'] = $_POST['name']; // Assign $_POST value to $_SESSION variable
header('Location: refresh.php'); // Address of this - reloaded page - in this case similar to PHP_SELF
} else session_destroy(); // kill session, depends on what you want to do / maybe unset() function will be enough
if(isset($_SESSION['name']))
{
$name = $_SESSION['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
</body>
</html>

Categories