...

View Full Version : How to pass a var from a file to a Javascript function via PHP?



RexxCrow
08-28-2007, 04:19 AM
I realized an issue with a portion of a project I am working on, I made a counter that keeps track of how many views a collapsed/hidden section receives via a mouse click on a link that makes that section visible. It turns out it increases the number with each page load rather then only once as I was wanting. I have since realized that PHP runs at loading and there does not seem to be anything you can do about it, though is there a way around this like calling the PHP from an external file once the JS function is activated and passing the variable back? TIA



function giveFlowers(roses){
var getV=document.getElementById(roses)
if(getV.style.display=='none'){
<?php
$cf=file("counter.txt");
$counter=$cf[0]; $counter++;
$fp=fopen("counter.txt", "w");
fwrite($fp, $counter);
fclose($fp);
?>
getV.style.display='block';
document.getElementById('content').style.display='none';
document.getElementById('flowers').style.cursor='default';
document.getElementById('flowers').innerHTML="<b>Replacement Text</b>";
self.focus('#focus');
}else if(getV.style.display=='block'){
self.close();
}
}

CFMaBiSmAd
08-28-2007, 04:52 AM
Perhaps some PHP 101 will help.

PHP runs on the web server when the page is requested (or refreshed.) So, even though the php code you posted is physically located inside of a javascript function and inside of a javascript conditional statement, that php code is unconditionally executed on the server when the page is served to the browser. The javascript code in the file has no meaning on the server. It is just literal content that is output to the browser.

Remember that the purpose of PHP is to output content (html/css/javascript) to the browser. It does not cause the javascript to be executed (that happens in the browser after the page has been sent to the browser) and javascript only has the ability to directly cause things to happen in the browser.

Specifically, here is what happens with the code you posted each time it is requested/refreshed -

The first three lines of javascript are output to the browser, because they are present outside of any <?php ... ?> tags (or you could use PHP echo statement(s) to output them to the browser if it was more convenient for them to exist within <?php ... ?> tags.) Your opening <?php tag is seen and the php code is executed, which reads the file, increments the counter, and writes it back to the file. Your closing ?> tag is seen and the remainder of the javascript code is output to the browser.

If we assume that that is all the code on the page, when the the last line on the page has been output to the browser, all the resources that were used by the page are destroyed, the web server forgets that it just served up one of your pages (except for what might have been written to a log file) and the web server goes on to serve other requests.

It is possible using AJAX techniques to cause javascript to make http requests to a web server so that data may be exchanged, but for what you are doing, I don't think this is necessary.

RexxCrow
08-28-2007, 05:09 AM
Thanks for the information, though is there any way to keep the PHP from modifying the count file until the JS function is called?

Erindesign
08-28-2007, 05:16 AM
I had a script, that would run a php snippet when a function was excecuted and it worked.



<script language="Javascript">
function update()
{
document.write = '<?php DO W/E ?>';
}
</script>


THe only thing I see wrond with this, is that you would have to use php for the views, and mysql. Inside the <?php update mysql databse with +1 views, and do a link with the button like:

<a href=# onclick="update()"> Expand/Collapse </a>

Fumigator
08-28-2007, 05:21 AM
Erindesign that does NOT "run a PHP snippet" when the function is executed. As CFMaBiSmAd mentioned, PHP is done with the file by the time Javascript gets a hold of it. The only thing you can do is pre-define a Javascript function (or assign a Javascript variable, or build and array, etc), but the only way to dynamically interact with PHP is by using Ajax or something similar.

RexxCrow
08-28-2007, 05:31 AM
...or is it also possible to write into the file as PHP lets you do via ECHO? Something like this?




...set something that will write or append to the page within the JS function when/if it is actually called by the user... somehow?

i.e.

function giveFlowers(roses){
var getV=document.getElementById(roses)
if(getV.style.display=='none'){
echo "<?php
$passVar="<?php
$cf=file("counter.txt");
$counter=$cf[0]; $counter++;
$fp=fopen("counter.txt", "w");
fwrite($fp, $counter);
fclose($fp);
?>"

CFMaBiSmAd
08-28-2007, 05:38 AM
Erindesign, if you find or reproduce some working code that is constructed the way you have it in your post, browse to it and before you click on anything that would cause the javascript to be executed, use your browser's "view source" and you will see that the results of the PHP code execution is already present in the code in the page in the browser.

It is true that the document.write() displays the content, but it is displaying content that was already present in its' final form. It did not cause any PHP code to be executed.

If I remember correctly, there was another recent thread, in the past few weeks, that addressed this same subject.

CFMaBiSmAd
08-28-2007, 05:50 AM
This will help - http://www.w3schools.com/ajax/ajax_httprequest.asp

If you want to send a piece of information to or even just signal a web server to increment a count based on an event happening in a browser, and you don't want to refresh the whole page, you are going to need to use a XMLHttpRequest object.

RexxCrow
08-28-2007, 06:23 AM
I tried the document.write and that either only prints the variable name to the screen or hangs the browser up.

RexxCrow
08-28-2007, 06:52 AM
Outstanding I scraped this together and it seems to be working as desired, thx much.


var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Sorry, Your browser does not support AJAX! Unable to Update Flower Count. Please visit www.GetFireFox.com");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","Counter.PHP",true);
xmlHttp.send(null);

Erindesign
08-29-2007, 02:49 AM
Well:

I was recently using a cool little vacation gallery that would set a cookie if person clicked on an image, and i did the onclick function, with a php set cookie option. It seemed to work awsomely.



document.write = '<?php $value="true"; setcookie("time","$value", time()+7200,"/"); ?>';


I know it worked, because when people would go to the page, without clicking the image, it would display a message saying take a look at the latest users. If it was clicked, it wouldn't show it.

Inigoesdr
08-29-2007, 06:41 AM
That's amazing! You found a way to circumvent the whole php being server-side problem. And the browser executed the php code too? Fantabulous.

CFMaBiSmAd
08-29-2007, 07:13 AM
That's amazing too, because the document.write = part of that is syntactically incorrect and just produces an error on the page in the browser (tested.)

Erindesign, the reason your code seemed to work had nothing to do with the onclick or any other javascript. Cookies are not available in the code on the page where they are set, until that page is refreshed or you request another page within the same domain that that cookie is valid for (clicking on a link to that page or another page within your domain.)

From the PHP manual for the setcookie() function -

Common Pitfalls:

Cookies will not become visible until the next loading of a page that the cookie should be visible for...

Erindesign
08-29-2007, 02:36 PM
I think I tried that, and it seemed that cookies weren't set. I don't have time now, but I will do it later on today to see if it actually works, or it was just my mistake (most likely since noone agrees with me).

CFMaBiSmAd
08-29-2007, 03:15 PM
A quick test - if you have a web page with that code on it, view the source of the page in your browser and tell us what you see.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum