Passing variables on the same page - php

The user enters a number and clicks submit. The number now shows up on the page.
The user is then asked if they would like to double the number. They click yes.
The doubled number now appears on the page.
I am having trouble with part 3. Is this possible using just PHP?
UPDATE: Thanks for your answers. This is my first ever PHP script, so I wasn't sure. I am going to research doing it with AJAX just now. I'm very curious to know why it is possible to get to part 2 if you can't get to part 3. Can anyone explain this or provide a link?

<?php
$double = (isset($_REQUEST['do_double']) && $_REQUEST['do_double'] == '1') ? ($_REQUEST['number'] * 2) : '';
?>
<form method="get" action="?">
<input type="hidden" name="do_double" value="<?php echo isset($_REQUEST['number']) ?'1' : '0'; ?>" />
<input type="text" name="number" value="<?php echo isset($_REQUEST['number']) ? $_REQUEST['number'] : '';?>" />
<?php if ( ! isset($_REQUEST['number'])) { ?>
<input type="submit" value="submit" />
<?php } else { ?>
<input type="submit" value="Verdoppeln" />
<?php } ?>
</form>
<div id="number"><?php echo $double; ?></div>

I think you're talking about session variables. At the top of the script add the following script to start a session for the current user:
session_start();
This will allow you to store variables in session $_SESSION which persists between requests. Use isset to check if a value is set in session.

Take the form ID using something like document.formname.inputname (http://www.quirksmode.org/js/forms.html) and then multiple by two then use javascript to show it where ever you want.

Asynchronous is required I think. Try these 2 reads:
the difference between synchronous and async: http://javascript.about.com/od/ajax/a/ajaxasyn.htm and
possible examples: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

This is really more of a comment than an answer, but SO limits comment length so here 'tis:
The misconception that a web page is synonymous with a PHP script appears to be common among novice PHP programmers. Really, a web page is an HTML document (with associated resources) that is sent from a web server to a web browser as part of an HTTP response. A single server-side script can generate many different kinds of web pages, and when processing HTML forms (as you seem to be doing) it is common for a single server-side script to do exactly that. In "web 1.0" applications, clicking on "Submit" (for example) typically causes the browser to make a new HTTP request (called a "page turn"), and the web server keeps track of what the user is doing across page turns by storing "state" either in a "session" (with an associated key included in the HTTP header of each HTTP request - and the HTTP response generated by the web "login") or in one or more HTTP parameters. The point is that each new HTTP request may be for the same script/URL on the server, but the behavior (and the appearance of the web page) will be different because the server is somehow tracking the state of the "workflow" across page turns.
Now if you really must avoid page turns, you can use Javascript to change the appearance/state of the page displayed by the browser without making the user click on a "Submit" button. And the XMLHTTPRequest mechanism (aka AJAX), which allows content to be fetched from the web server "behind the scenes" and change the state of the client-side document without the user doing anything, is typically used to achieve this. But is only really necessary if you're doing something rather different (e.g. scrolling a map or updating a stock ticker) than what you describe in your question, which looks like a perfect example of a "web 1.0" application workflow.

Related

GET method appeared in $_SERVER before submit

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return checkValid(this)" method="GET">
<input type="text" name="Symbol">
<input type="submit" name="submit" value="Search">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "GET"){
echo "test";
$CSymbol = $_GET["Symbol"];}
?>
when the page was first load and did not press submit button, the php was executed and "test" was print on the screen, also with error:
Notice: Undefined index: Symbol in test.php on line 179
but if i change everything to POST, problem solved. Why is that, what's different btn GET and POST?
GET values are sent in the URL, POST in the HTTP Body. So "GETting" values can alsways be done but may be empty. POST has to be manually created. If you want to use GET in this case however. Guard it:
<?php
if($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET["Symbol"]){
echo "test";
$CSymbol = $_GET["Symbol"];}
?>
Reference Link
GET and POST are two different types of HTTP requests.
According to WikiPedia:
GET requests a representation of the specified resource. Note that GET should
not be used for operations that cause side-effects, such as using it for taking
actions in web applications. One reason for this is that GET may be used
arbitrarily by robots or crawlers, which should not need to consider the side
effects that a request should cause.
and
POST submits data to be processed (e.g., from an HTML form) to the identified
resource. The data is included in the body of the request. This may result in
the creation of a new resource or the updates of existing resources or both.
So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.
Authors of services which use the HTTP protocol SHOULD NOT use GET based forms
for the submission of sensitive data, because this will cause this data to be
encoded in the Request-URI. Many existing servers, proxies, and user agents will
log the request URI in some place where it might be visible to third parties.
Servers can use POST-based form submission instead
Finally, an important consideration when using GET for AJAX requests is that some browsers - IE in particular - will cache the results of a GET request. So if you, for example, poll using the same GET request you will always get back the same results, even if the data you are querying is being updated server-side. One way to alleviate this problem is to make the URL unique for each request by appending a timestamp.
For your above code..
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return checkValid(this)" method="GET">
<input type="text" name="Symbol">
<input type="submit" name="submit" value="Search">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "GET" && !empty($_GET['Symbol'])){
echo "test";
$CSymbol = $_GET["Symbol"];}
?>
Every http request that is not a POST counts as a GET request, and so every page that loads up has an empty GET request, php will create a super global $_GET array with every non post request.
Hope this helps you understand what is going on.

$_SESSION variable used to check if form has been submitted

I have a landing page called `index.php' with the following form:
<form action="auto_mail.php" method="post">
<input id="signup" class="span8" type="text" placeholder="Your email" name="signup">
<input type="submit">
<?php
if (isset($_SESSION['got_it']))
{echo "<b>You're all signed up!</b>}
?></form>
In the file auto_mail.php I have:
// code scrubbing user input...
$user_email = $_POST['signup'];
session_start();
$_SESSION['got_it'] = '1';
// code sending me an email when someone signs up.
echo <<<EOD
</b>
<meta http-equiv="refresh" content="0, url=index.php">
</div>
</body>
</html>
EOD;
?>
I've looked at some other SO questions (Using $_SESSION to carry data), but it's not what I'm looking for.
All I want, is for a user to see "You're all signed up" when they enter a valid email; with the email confirm email being sent in the background. This code feels clumsy and awkward. It also flashes the auto_mail.php page briefly.
I tried to set <form action="index.php"..., but it doesn't work because I've set up auto_mail.php such that you can't access it directly.
How can use the code in auto_mail.php, which checks for a valid email address and sends confirm emails, without dealing with both $_POST and $_SESSION, or at least using them better?
If you don't want to have any page reloads whatsoever, you'll have to use AJAX to send the form, instead of utilising the form POST.
If you are using jQuery, or Mootools, they both have built in wrappers to handle ajax calls. Without a helper library, you'll have to look into making an XMLHttpRequest yourself.
Other than that, traditionally, you would redirect the user to a "form submitted" page, or alternatively, have the form action be sent to the same page (in your case, index.php, and have PHP code to handle form data if it is received).
I dont get completely what you want.
I think you try to Verify a Mail Address (after?) that form has been sent. But you cannot access the file via http that does the verification.
Have you thought about including the auto_mail.php?
I think you should consider using one of popular PHP frameworks. I guess you didn't use any in above example. Good framework that also offers MVC structure allows to do operations like this in such a simple way you can't even imagine.
Breaking it down to MVC structure will even make it extremely simple to handle post sending and displaying dependences and results made by it in one action.
Learing good framework at first might look like a waste of time, but believe me - it will pay off very quickly.
For start I recommend you looking at Kohana Framework or, if you're ambitions one - Symfony Framework.

How to Send Form Data to an External Database and Process It?

In one site, www.example.com, I have a form. It is processed and stored in its database.
Is it possible to send this form data also to another site (www.client-site.com)? It is located on a different server. And this client-site should receive the data and store it on its own database.
I am not sure of the terminology and what should I've been looking for.
Tested different search queries here in SO and this is what most resembles it:
[php] [mysql] +form +"$_post" +external
I'd like to develop this with PHP and the databases run MySQL, and surely security is important in this data transaction.
And hoping this is not a SOAP matter... ;)
Justification:
www.example.com runs a mini site of one of my clients
www.client-site.com is the client main site
being a large company, they cannot provide me credentials to their main site database
I have to propose an alternate solution
You will need to have something like a webservice (this is the word you are looking for) on site b which you can use from the code within your site a.
SOAP is one possibility to create a webservice, but there are many other possibilities. One is shown in this answer on stackoverflow.
NEVER EVER try to archiv this using forms and something like cURL!
Further you should look for proper authorization on your endpoint (site b) and ensure that ssl is used, as security is important to you.
If you have a form hosted on www.example.com like this:
<form method="post" action="http://www.client-site.com/handler.php">
...
Then the page http://www.client-site.com/handler.php will be able to access the post variables.
This is why it is important that you validate your post data in your own PHP applications as you can never be sure where the data is coming from and therefore cannot trust it.
I can think of a very ugly solution wich will do the trick :)
<script language="JavaScript">
function submitForm(theform) {
theform.action = "SITE ONE";
theform.target="myframe1";
theform.submit();
theform.target="";
theform.action = "SITE2";
theform.submit();
}
</script>
<html>
<body>
<form action="" onSubmit="submitForm(this); return false;">
<input type="text" name="userName" value="" />
<input type="Submit" />
</form>
<IFRAME name="myframe1" src="about:blank" width="0"
height="0"></IFRAME>
</body>
</html>
This is not so conventional but will do the trick !
check it out :)

Sending form data to one page, then another?

I'm having a bit of trouble with this one, as basic as it may be. I have a simple form with name, email, comments, etc. that outputs itself to one php page, but I want to have a link that sends it to a second page, for example:
<label for="name">Name:</label><input type="text" name="name" size="20" />
Goes to a second page (second.php) with this code and prints it just fine:
print "<div>Thank you, $name.</p></div>";
But if I try to send $name to a third page (third.php) using similar code it shows up like this:
Thank you, $name.
With the actual variable and not what was stored in $name.
I feel like I'm missing one tiny little thing but I'm not sure what it is. I used this:
$name = $_POST['name'];
To bring it to second.php and this to bring it to third.php:
print 'Click here to proceed.';
Just to see if it would get the same information from second.php, but I don't think it works that way. Is there something else I should be doing on the third page? I have a feeling it's something incredibly insignificant but as I'm learning, I just can't quite get a grasp on it.
You can do it this way.
when you declare
$name = $_POST['name'];
you can use in a header to pass this variable
if(isset($_POST['btnname']))
{
header('Location: second.php?name='.$name);
}
The in your second php
you can get it by this way
Thank you, <php echo $_GET['name']; ?>
Or if you want it to be available to all pages use session
$_SESSION['name'] = $_POST['name'];
=D
you can try it using a hidden input
<label for="name">Name:</label>
<input type="hidden" name="name" value="<? echo $name; ?>" size="20" />
Websites are stateless, which means that the variables only last for a few seconds on the server, then the html is rendered, and sent to the clients browser. The server memory is then freed up to serve other clients.
You have a few options:
1) Using a hidden form field and printing (with php) their name to the hidden form field so when they post again it gets saved (if they post again).
2) Sessions
3) cookies
4) Print it out in the url (i.e. page.php?name=".$name; )
It all depends on how you get to your third page (From a link? A form? A php redirect?)
You can store the name in the second page and again set the $_GET variable before the third page is called. This is because the variables are only valid for that particular request and they need to be set again when another request is made.

Javascript redirect vs form submit to a php script

I've got a form on my websites homepage that contains a box for a user to enter a members name. From there the form currently submits to a PHP script which just calls Header('Location: blah); and then directs them to /search/username/.
Would it be worth it (i'm assuming so) doing that redirection in javascript so that directs them straight to /search/username? If so how would I go about redirecting with javascript, just plain old window.location = "http://www.google.com/"
Server side is always better method as it's more difficult to bypass than client side method.
Be sure to add exit function after redirection using header.
ob_clean();
header('Location: target.php');
exit();
To do it in JavaScript, you could:
<input id="username" type="text" onclick="" />
<input type="button" onclick="window.location='/search/'+document.getElementById('username').value" />
You could add some validation to the event as well.
Would it be worth it
That depends on your specific situation. If your server is getting 100's of these requests a second, then sure. Otherwise, it really doesn't matter which way you do it.

Categories