PHP GET variable in same document
how can i pass a variable from javascript to php using same file
in this example page keeps refreshing and i don't get to see the result
it works only if i separate the scripts... but i need it somehow like on ajax..
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="开发者_StackOverflow社区http://localhost/put.php?Result=" + carname;
</SCRIPT>
and this is the seccond part of the script ( they are both in same file )
<?php
Id = $_GET[Result];
echo $dbId;
?>
As Brian said you should put it in a conditional statement.. also your PHP is bad. Try the following
<?php if(isset($_GET["Result"])) : ?>
// do work with set variable
<?php $dbID = $_GET["Result"];
echo($dbID); ?>
<?php else : ?>
// "Result" not set
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
<? endif; ?>
I think this is a good exercise if you're trying to learn the Ajax method, in the real world I recommend using a framework like jQuery. Of course understanding how this works will help you build better applications in the end.
So you could do something like this in the PHP script:
if (!isset($_GET['Result']))
{
// include the javascript portion with the redirect
}
I'm with the others, though--I'm not seeing the value in a page load followed by an immediate redirect to the same page.
What you are trying to do cannot be done. Your script runs on the client in real time but the php will run on the server during the request. You will need to make an AJAX request.
First you will want to use Firefox with firebug and the web developer toolbar. Firebug gives a great view of ajax traffic and the web developer toolbar helps you see what's going on in the page.
Use jQuery make an ajax request to "send" the value to another php file. Don't be afraid to separate out files, in fact it's encouraged and considered good programming. If you find your sending a lot if information to a php script you will want to use JSON instead of as part of the url.
Man, you should follow a client-server pattern.. So the Client page can use some ajax to make a request to a Server page. This will response to the Client and you can make with the data what you want.
of course it will keep refreshing:)) Because as soon as the browser gets the js code, it will load that page you specify, which will send your browser the same page... you get the idea. It's like writing for(;;){}
Your question is difficult to understand (for me at least.) My guess is that you are wanting to use AJAX to send data to the server and receive a response without leaving the page.
Probably the easiest way to accomplish this is to use a library such as jQuery. (see jQuery.ajax())
PHP only runs on the server and the javascript only runs on the client. By the time your client is running the javascript, no more PHP can be executed on that request.
精彩评论