Page 1 of 1

putting javascript variables into php file

Posted: Wed Jun 26, 2002 3:07 pm
by bhaggert
Sorry if this has been answered before, I didn't see it when I searched the archives.

I have a javascript variable that I need to pass into a PHP block:
<script language="JavaScript">
<!-- Begin
function checkRadios() {

storeNum = document.storeSelector.storeRadio.value;
<?php
$storesVisited = fopen("beenthere_$NetID.txt" , "a+");//open file for

$storeNum = storeNum; //set PHP variable to JS variable
echo "alert($storeNum);";
fputs($storesVisited , $storeNum); //write variable to file
fclose($storesVisited); //close file
echo "alert($storeNum);";
?>

return true;
}
// End -->
</script>

The alerts both work as expected and output the contents of the JS variable (e.g. "Store1").
When viewing the text file however it has the variable name "storeNum", not the contents of the variable.
Help!?

PLease respond soonest as this is the last hangup to complete a project.

TIA,

Bryan

Posted: Thu Jun 27, 2002 1:48 am
by twigletmac
Have you read this:
http://www.devnetwork.net/forums/viewtopic.php?t=1030

Basically the PHP is run on the server so it has already executed before everything reaches the browser and the Javascript is run. It's relatively easy to pass PHP variables to Javascript but the other way round is a different story...

Mac

Posted: Thu Jun 27, 2002 9:59 am
by bhaggert
Thanks for the reply. I've read teh article and I understand clientside/serverside programming concepts.

What I don't understand is why the JS alert 'knows' the contents for the variable but the next line that writes to te file doesn't.

Posted: Thu Jun 27, 2002 12:02 pm
by twigletmac
It's because you are sending the alert box the Javascript variable storeNum because the PHP variable $storeNum is equal to the string 'storeNum'. PHP knows nothing about Javascript all it sees is a bunch of strings it doesn't know what the value of storeNum is. So alert(storeNum) works because the Javascript variable storeNum has been set and when you write to the file you get the value of the PHP variable $storeNum which is 'storeNum' and not the Javascript variable storeNum.

Hopefully that makes some sense to you because I've started to confuse myself...

Mac

Posted: Sun Jun 30, 2002 10:19 pm
by FireyIce01
If you use document.write (into a hidden DIV would be my suggestion) you can write a dynamic form, and in the form, you can make variables, eg, <input type=hidden name=storeNum value='whatever'> and then post the form to the PHP, and that will pass the variables, beyond that I don't know what to suggest... if you come up with something let me know!