Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    Regular Coder RexxCrow's Avatar
    Join Date
    Jul 2006
    Location
    California
    Posts
    275
    Thanks
    6
    Thanked 2 Times in 2 Posts

    How to pass a var from a file to a Javascript function via PHP?

    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


    Code:
    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();
     }
    }

  • #2
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,107
    Thanks
    2
    Thanked 326 Times in 318 Posts
    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.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #3
    Regular Coder RexxCrow's Avatar
    Join Date
    Jul 2006
    Location
    California
    Posts
    275
    Thanks
    6
    Thanked 2 Times in 2 Posts
    Thanks for the information, though is there any way to keep the PHP from modifying the count file until the JS function is called?

  • #4
    Regular Coder
    Join Date
    Apr 2006
    Posts
    231
    Thanks
    9
    Thanked 1 Time in 1 Post
    I had a script, that would run a php snippet when a function was excecuted and it worked.

    PHP Code:
    <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>

  • #5
    UE Antagonizer Fumigator's Avatar
    Join Date
    Dec 2005
    Location
    Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
    Posts
    7,691
    Thanks
    42
    Thanked 637 Times in 625 Posts
    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.

  • #6
    Regular Coder RexxCrow's Avatar
    Join Date
    Jul 2006
    Location
    California
    Posts
    275
    Thanks
    6
    Thanked 2 Times in 2 Posts
    ...or is it also possible to write into the file as PHP lets you do via ECHO? Something like this?


    Code:
    ...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);
    ?>"

  • #7
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,107
    Thanks
    2
    Thanked 326 Times in 318 Posts
    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.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #8
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,107
    Thanks
    2
    Thanked 326 Times in 318 Posts
    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.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #9
    Regular Coder RexxCrow's Avatar
    Join Date
    Jul 2006
    Location
    California
    Posts
    275
    Thanks
    6
    Thanked 2 Times in 2 Posts
    I tried the document.write and that either only prints the variable name to the screen or hangs the browser up.

  • #10
    Regular Coder RexxCrow's Avatar
    Join Date
    Jul 2006
    Location
    California
    Posts
    275
    Thanks
    6
    Thanked 2 Times in 2 Posts
    Outstanding I scraped this together and it seems to be working as desired, thx much.

    Code:
    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);

  • #11
    Regular Coder
    Join Date
    Apr 2006
    Posts
    231
    Thanks
    9
    Thanked 1 Time in 1 Post
    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.

    PHP Code:
    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.

  • #12
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    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.

  • #13
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,107
    Thanks
    2
    Thanked 326 Times in 318 Posts
    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...
    Last edited by CFMaBiSmAd; 08-29-2007 at 06:23 AM.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #14
    Regular Coder
    Join Date
    Apr 2006
    Posts
    231
    Thanks
    9
    Thanked 1 Time in 1 Post
    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).

  • #15
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    3,107
    Thanks
    2
    Thanked 326 Times in 318 Posts
    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.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •