Forum Moderators: open

Message Too Old, No Replies

php and javascript

         

levrek1

4:27 pm on Oct 24, 2004 (gmt 0)



I keep seeing postings indicating that you can use PHP together with javascript, for example, in the following way:

<script language="javascript"><!--
for(i=0; i<=1; i++){
var message="<?php echo $t[i];?>"; //quotes outside php
document.write(message);
}
//-->
</script>

But, one key reason for using this construct is to use a javascript variable in the php request--and this doesn't work for me. For example in the script:

<script language="JavaScript">
<!--
var loginName="myfile.txt";
var command = "<?php $fh =" + loginName + "; $infile=file($fh); for($i = 0;$i<count($infile);$i++){ $test = $test . $infile[$i];}?>";
document.write (command);
var buddylist='<?=$test?>';
<script>

...PHP never seems to get the value of "loginName". Instead it says that it can't find the file called "loginName". This holds true whether I use single or double quotes.

How do you get the value of a javascript variable into the PHP line? (by the way, for this application, I can't do it all on the server with PHP)

Lance

4:40 pm on Oct 24, 2004 (gmt 0)

10+ Year Member



First let me say that I'm no expert here...

That said, server side scripting is processed before the page is rendered. By the time your j/s runs on the client, it's too late to set a PHP command. PHP needs to have the value before the page starts writing.

I hope that makes sense. Someone else will probably explain this far better.

StupidScript

4:41 pm on Oct 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



(Oop! Crossed our posts, Lance. You're right!) Keep in mind that PHP acts on the code before the document is delivered to the client, and Javascript acts on the code after it has been delivered to the client. You seem to be trying to run a PHP script based on information which is only available after (or before) PHP has a chance to see it.

Generally, you will pass Javascript variable back to PHP on the server by sending it as part of a request.

For example:

var giveToPHP="forPHP.php?loginName="+loginName;
buddyFrame=document.getElementById("buddyFrame");
buddyFrame.src=giveToPHP;
//might be buddyFrame.location.href ... sorry I'm not certain

will target an iframe and reload a php page that can grab the "loginName" variable passed from the Javascript.

Javascript can pass variables to PHP by sending a request, and PHP can pass variables to Javascript by compiling info before delivering a request.