Response from one page to another page in php without ajax - php

I am just started with Php and have some doubts.
I created 2 pages one.php and two.php
ONE.php
<body>
<form method="post" action="TWO.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
</body>
TWO.php
<body>
<?php
$sum=$_POST["txt1"] + $_POST["txt2"];
echo $sum;
?>
</body>
I POST values form one.php to two.php. Two.php calculates the sum and echo's the result.
My query is would I be able to get the sum echoed on one.php using just php and its important to post the data on another page and get the response from there.

Yes you are. Simply, handle the form submission (the POST request) in one.php. When the request for one.php is not POST just show the form.
The typical way is:
// ONE.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$content = "Sum is " . $_POST["txt1"] + $_POST["txt2"];
}
else {
$content = <<<EOC
<form method="post" action="ONE.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
EOC;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ONE</title>
<meta charset="utf-8"> <!-- or whatever charset you are using -->
</head>
<body>
<?php echo $content ?>
</body>
</html>
Edited, the OP needs the two files but print the result on one.php
In order to pass data between two files you can:
Set the data in the first file (two.php) and require the second (one.php, where you would print the value)
Use PHP sessions.
With the latter you need to do a (well you don't need to but it's mean to work with a) page redirect, so my recommended approach for this case is use the former. The code could be something like:
// TWO.php
<?php
// you should probably check if $_POST['txt1'] and $_POST['txt2'] does really exists and throw and error if not...
$sum = $_POST["txt1"] + $_POST["txt2"];
require "ONE.php" // careful if you're on a *nix file system the NameCase is extremely important!
// ONE.php
<?php
if (isset($sum)) {
$content = "Sum is " . $sum;
}
else {
$content = <<<EOC
<form method="post" action="TWO.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
EOC;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ONE</title>
<meta charset="utf-8"> <!-- or whatever charset you are using -->
</head>
<body>
<?php echo $content ?>
</body>
</html>

Try this code:
<body>
<?php
if($_POST){
$sum = $_POST["txt1"] + $_POST["txt2"];
echo $sum;
}else{
?>
<form method="post" action="">
First Number<input type="text" name="txt1"><br />
Second Number<input type="text" name="txt2"><br />
<input type="submit">
</form>
<?php } ?>
</body>

You can try with this, in only one page:
ONE.php
<html>
<head></head>
<body>
<form method="post" action="ONE.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
<?php
// Verify if $_POST["txt1"] and $_POST["txt1"] are defined
// (when form is submit $_POST, $_GET and other $_ PHP vars
// are set). If form isn't submitted, set 0 on each variable
// to perform sum. Is necessary check values to avoid PHP
// Warnings/Errors (In this case with isset function. There
// are many different ways to perform it)
$txt1 = isset($_POST["txt1"]) ? $_POST["txt1"] : 0;
$txt2 = isset($_POST["txt2"]) ? $_POST["txt2"] : 0;
$sum = $txt1 + $txt2;
//Print sum result
echo 'Sum is: '.$sum;
?>
</body>
</html>
For comparations I'm using ternary operators, that simplify/minimize code of traditional if/else. Also you can use traditional if/else (simple compare) or switch(multiple compare)

Related

How to keep value after post request?

I want to learn how to keep value after a post request.
In my code, I have these variables:
myvar
myans
result
myvar is a random val between 0-5. I will get myans from my input if myans == myvar, then result will be true (else it will be false).
I see myvar before I submit my ans just for trying, but although I see the var when I send it, what I see it is sometimes false and sometimes true. What am I missing?
example.php:
<?php
session_start();
if (!isset($_COOKIE['result'])) {
setcookie("result","EMPTY");
}
setcookie("myvar",rand(0,5));
if (!empty($_POST)) {
if ($_POST['myans'] == $_COOKIE['myvar']) {
setcookie("result","TRUE");
}
else {
setcookie("result","FALSE");
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo $_COOKIE['myvar'] ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo $_COOKIE['result'] ?>
</form>
</body>
</html>
The problem you were having was caused by your random number generator making creating a new number before comparing to the original. I made some changes to only set "myvar" if it's empty. this will only set it once, but at least you can see your code working as intended. I recommend you plan out what exactly what functionality you want before adding to it.
I also switched you out from the "$_COOKIE" var to "$_SESSION" vars. They are hidden from the client, and by php default last about 24 minutes if not refreshed. I don't know what you plan on using this for, but using cookies allows the end user to manipulate that info. If this is not a concern for you, by all means just uncomment the "setcookie()" lines.
<?php
session_start();
if (!isset($_SESSION['result'])) {
//setcookie("result","EMPTY");
$_SESSION["result"] = "EMPTY";
}
//setcookie("myvar",rand(0,5));
if(empty($_SESSION["myvar"])){
$_SESSION["myvar"] = rand(0,5);
}
//
if (!empty($_POST)) {
if ($_POST['myans'] == $_SESSION['myvar']) {
//setcookie("result","TRUE");
$_SESSION["result"] = "TRUE";
} else {
//setcookie("result","FALSE");
$_SESSION["result"] = "FALSE";
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo isset($_SESSION['myvar']) ? $_SESSION['myvar'] : ""; ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo isset($_SESSION['result']) ? $_SESSION['result'] : ""; ?>
</form>
</body>
</html>

PHP - Can't submit form to handler

Here is my Code :
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form id="form1" action="../../../wamp/www/abc.php" method="get">
<input type="text" name="text1" id="username" />
<input type="submit" />
</form>
</body>
</html>
The abc.php file is located in C:/wamp/www/abc.php
<html>
<body>
Hello World
<?php
echo "Hello";
echo $_GET["username"];
?>
</body>
</html>
In the form, when I press the Submit button, only "Hello World" is displayed.
The value entered in the textbox is not displayed at all. Even the "Hello" message printed inside the php code is not displayed.
How can i display the Value ?
text1 is the name of your input, so the correct PHP code would be.
<?php
echo "Hello ";
echo $_GET['text1'];
?>
Try the below, get array is created using name attr not id one.
echo $_GET["text1"];
There is two solution for you should use :
First Way :Change your php code:
<?php
echo "hello";
echo $_GET["text1"];
?>
Second Way: Chnage your HTML
<input type="text" name="username" id="username"/>
If second "Hello" from echo is not displayed, there is a problem with your PHP installation.

POST variable doesn't echo in function

I am currently learning the most basic PHP ever. I have 5 files.
index.php:
<html>
<head>
<title>Budget Calcule</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Put in your: - </h2>
<form action="functions.php" method="post">
<h3>Income</h3>
<label>Salary: <input name="salary" type="text" /></label><br />
<h3>Outgoings</h3>
<label>Living: <input name="living" type="text" /></label><br />
<label>Insurance: <input name="insurance" type="text" /></label><br />
<label>Communication: <input name="communication" type="text" /></label><br />
<label>Loan: <input name="loan" type="text" /></label><br />
<label>Food & Drink: <input name="foodAndDrink" type="text" /></label><br />
<label>Entertaintment / Shopping: <input name="entertainmentOrShopping" type="text" /></label><br />
<label>Transport: <input name="transport" type="text" /></label><br />
<label>Other: <input name="other" type="text" /></label><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
this is my functions.php:
<?php
include('variables.php');
if(!($_POST['Submit'])){
if(isset($_POST['salary'])){
header('Location: output.php');
return $_POST['lon'];
}else{
echo "All fields are required";
}
}
?>
this is my variables.php:
<?php
$salary= $_POST['salary'];
$living= $_POST['living'];
$insurance= $_POST['insurance'];
$communication = $_POST['communication'];
$loan = $_POST['loan'];
$food = $_POST['food'];
$entertaintmentOrShopping = $_POST['entertaintmentOrShopping'];
$transport = $_POST['transport'];
$other= $_POST['other'];
?>
this is my output.php file:
<?php
include('outputFunction.php');
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
and last but not least, this is my outputFunction.php file:
<?php
include('variables.php');
function myText(){
echo "Your salary per month is: " . $_POST['salary'];
}
?>
Now you're thinking "why have he split up his code in different files?" Well first of all, I split the variables from functions.php because I wanted outputFunctions.php to get the variables from variables.php so i could echo my `$_POST['salary']; . The function myText(); outputs the text just fine, but it doesnt output the $_POST['salary'];.
I do not know why it doesnt work, I just wonder if you could be my extra eyes and see if I've done some mistake.
PS! Don't down vote my question just because you think it's stupid. I am having problem with this issue and been working on it for hours without advancing anywhere.
A few things:
You don't need to include a variables.php file. The variables you're accessing are global and you're just creating duplicates that aren't being used. They also go away after the page changes since you're re-declaring them each page load.
You are also trying to call a variable that doesn't exist when you reference $_POST['lon'] instead of 'loan'.
And finally to actually answer your question:
Your myText() function is referencing a variable that is not there anymore.
You need to merge functions.php and outputFunction.php and output.php into one file so the variables aren't lost and all the processing is done without opening a new file each time. I can see your original concept for separated files but an output file is going to be the file to process the input data from the form.
Now in your newly merged output.php, you should have something resembling this:
<html>
<head>
<title>Output</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
echo "Your salary per month is: " . $_POST['salary'];
}
} else {
echo "All fields required.";
}
?>
</body>
</html>
This means only two files - your form page and this page.
A few more tips:
If you want to check if the form was submitted, it has look something like this:
if(isset($_POST['Submit'])){ ... }
Also, you should add a name="" attribute to your submit-Button:
<input type="submit" name="Submit" value="Submit" />
And what is the variables.php for? You don't use any of those variables.
When you redirect the user via header() the data that is stored in the $_POST array gets lost.
You could directly redirect to ouput.php
<form action="output.php" method="post">
And do something like this:
<?php
include('outputFunction.php');
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
<?php
} else {
echo "All field required";
}
}
?>
By the way you can always check what your $_POST contains with print_r($_POST);
This can be very useful for debugging.

PHP Pass variable up the page

I came across someone asking the question,
How can I pass a variable up the page (on the same page?).
I had a think about it but couldn't think of how to do it myself, so I was wondering if it is even possible?
So what he was trying to do was change the value of $a at the top of the page at the same time as the bottom value of $a.
Is it possible? If so how?
Thanks in advanced.
<?php
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
if ("submit" == $submit) {
$a = $testf;
echo( "Bottom " . $a);
}
?>
</body></html>
Edit:
After seeing answers, maybe it can be done with jquery, ajax or javascript?
No, you'll need to move the if statement to the top, and any variables you calculate that need to be in the if statement also to the top.
Something like:
<?php
if ("submit" == $submit) {
$a = $testf;
}
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
echo( "Bottom " . $a);
?>
</body></html>
It's considered a good practice to have all the logic before you start outputting the HTML anyways. Your HTML should ideally have as less logic as possible.
More info: https://stackoverflow.com/a/95027/320615 and https://stackoverflow.com/a/1088791/320615
You can probably bend over backwards to make that work somehow.
But the real answer is to handle all your business logic before you start outputting any HTML. You need to decide at the beginning of your code whether the current request is a form submission or not and set variables and HTML templates accordingly. Never mix business logic into the middle of your HTML templates.
You have to use the $_POST['testf'] and $_POST['submit'] variable.
And also check if it exists with isset : php manual isset
<?php
echo("Begining " . $a);
?>
<html>
<head>
<title>Test Variables</title>
</head>
<body>
<form>
<form action="<?=$PHP_SELF?>" method="POST">
<input type="TEXT" name="testf" size="10">
<input type="submit" name = "submit" value = "submit"></form><?php
if ("submit" == $submit) {
$a = $_POST['testf'];
echo( "Bottom " . $a);
}
?>
</body></html>
You can't do it in PHP, but you can't change HTML once it's fully loaded using javascript (and jquery to make it easier).
EDIT : ok I read your code a bit quickly the first time :
I don't understand the echo before the <html> tag, doesn't seem right. Also you want to give the value of a POST var to $a, so just :
if(isset($_POST['testf'])) {
echo $_POST['testf'];
}

ECHO page1.php textarea values into page2.php

I have 2 php files in my folder. In page1.php, there's a textarea, user should enter some values in it. In page2.php, it will grab what is in the textarea and work with its program. But I can't find a command that grabs the value in textarea. Can someone help me?
page1.php:
<?
$hello = "hello";
?>
<html>
<input type = "text" name = "user_input">
</input>
</html>
page2.php
<?
ob_start();
include 'page1.php';
ob_end_clean();
echo $hello;
?>
So, is there anyone that can solve this? =/
Use $_GET or $_POST in page2.php
page1.php
<?
$hello = "hello";
?>
<html>
<form method="get" action="page2.php" enctype="multipart/form-data">
<input type = "text" name = "user_input">
<input type="submit">
</form>
</html>
page2.php
<?
$text=$_GET['user_input'];
ob_start();
include 'page1.php';
ob_end_clean();
echo $hello;
echo $text;
?>
You may use either $_GET['user_input'] or $_POST['user_input'].
The difference is, you can see the data in the url (visible to everyone) when using GET method and not in the other method.
Also, always use <input> elements (which you want to pass to another file) inside a <form> and specify action="file.php", to where you want to pass data, and the method, either method="get" or method="post", like;
<form method="get" action="page2.php">
also specify the method to grab data in the target file also, like;
$text=$_GET['user_input']; or $text=$_POST['user_input'];
And in your case, you may use;
Method 1
<?php
$hello = "hello";
?>
<html>
<form method="get" action="page2.php">
<input type="text" name="user_input">
<input type="submit">
</form>
</html>
page2.php
<?php
$text=$_GET['user_input'];
echo $text;
?>
Method 2
<?php
$hello = "hello";
?>
<html>
<form method="post" action="page2.php">
<input type="text" name="user_input">
<input type="submit">
</form>
</html>
page2.php
<?php
$text=$_POST['user_input'];
echo $text;
?>
If you want to share the data over a number of pages, you may do this using PHP Session or saving the data in a cookie.
1. Using Sessions
<?php
session_start();
$_SESSION['data'] = 1; // store session data
echo "Pageviews = ". $_SESSION['data']; //retrieve data
?>
Make sure you add session_start(); on every page you want to handle session
You can read more about php sessions here www.tizag.com/phpT/phpsessions.php/
2. Using Cookie
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
and retreive it using
echo $_COOKIE["user"];
You can read more about php sessions here http://www.w3schools.com/php/php_cookies.asp
hope this helps...:)
basically your page1.php is a page with some form in it with a text area. Now user will have to fill it and submit the form to page2.php. You can't echo it's content like that, because that will be on browser subject to user actions. Use a form and submit the data to page2.php. Like this:
page1.php
<html>
<head>
</head>
<body>
<form action="page2.php" method="post">
<textarea name="t1">
</textarea>
</form>
</body>
</html>
page2.php
<?php
$textAreaContents = isset($_POST['t1'])?$_POST['t1']:'';
echo "You submitted: ".$textAreaContents;
?>
if i were you i should use sessions for this. that is where they were made for..
example:when user clicks on submit.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$_SESSION['post'] = $_POST;
}
that is where every post variable will be put in a session.
and your inputbox will be something like this..
<textarea name="message" type="text" value="" rows="0" cols="0" placeholder="" ><?php if(isset($_SESSION['post'])){echo $_SESSION['post']['message'];} ?></textarea>
?>
note that you now can use every post variable that you used in your form by echo (example)
echo $_SESSION['post']['message']
where message is the name of the inputbox. in this case of the textarea
don't forget that at the end when you don't want to use the session anymore use session_destroy(); otherwise you will keep having it in your form. and don't forget session_start(); above every page where you are planning to use sessions ( it must be at 1st line of your document at all times)

Categories