Jump to content

Pass a Javascript Variable to PHP


hoopplaya4

Recommended Posts

It is possible to make a link submit a Javascript variable to php at any time but for php to process it in the main page would require a page reload. So basically you setup a link to an invisible iframe and add to the iframe url variables. Then when the iframe loads, it gets the url variables and converts them to session variables. Then those session variables are available to any new page that loads. An example is as follows:

<? //index.php
echo "<a href='iframe.php?myvar=test&var2=example' target='iframe'>test link.</a>";
echo "<iframe width=1 height=1 scrolling='no' name='iframe' frameborder=0 src='iframe.php'></iframe>";
?>

<? //iframe.php
session_start();
foreach ($_GET AS $key => $val)
{
$_SESSION[$key]=$val;
}
unset($key);
unset($val);
?>

In the example above, as soon as the user clicks the link, the following variables will be set:

$_SESSION['myvar']=test

$_SESSION['var2']=example

So it is possible to make variables set at any time but it is just processing or displaying them which is the real trouble.

Yes you could use iframes indeed and send the url parameters to that iframe. But why not simply use Ajax it's a lot simpler when you get the hang of it.

The ajax tutorial alpine wrote here a couple of years ago still works

http://www.phpfreaks.com/forums/index.php/topic,115581.0.html

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.