Thread: Php in .js file

    #1
  1. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,650
    Rep Power
    171

    Php in .js file


    Java script should be in an external js file otherwise wont be valid html.

    I have lots of dynamic values in my javascript that I generate with php. For example sliders that have max and min amount based on database values.

    What is the best way to use php in .js file?

    Thank you
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    Hi,

    Originally Posted by zxcvbnm
    Java script should be in an external js file otherwise wont be valid html.
    Says who? Maybe you mean it's not good (X)HTML, but it is perfectly valid to embed a script element with JavaScript.



    Originally Posted by zxcvbnm
    I have lots of dynamic values in my javascript that I generate with php. For example sliders that have max and min amount based on database values.

    What is the best way to use php in .js file?
    Just like you use it to generate HTML pages. The only difference is that you have to manually set the Content-type header to text/javascript.

    However, I wouldn't write PHP snippets into the JavaScript but rather use a template engine like Smarty. And you have to be very careful with what you insert. In a JavaScript context you cannot simply escape values to prevent them from being interpreted (unless you're in a string). So make sure you cast every number into an integer/a float before you insert it.
  4. #3
  5. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    I normally handle this by embedding the dynamic values in my main view, and linking to the main JavaScript externally.

    For example, my main view may look like this:
    Code:
    <script type="text/javascript">
      var value1 = <?php echo json_encode($value1); ?>;
      var value2 = <?php echo json_encode($value2); ?>;
      var value3 = <?php echo json_encode($value3); ?>;
    </script>
    <script type="text/javascript" src="js/jslogic.js"></script>
    Mostly because this method allows the bulk of the JS code to be loaded without the server needing to invoke PHP, which helps a lot with performance. It also allows clients to cache the JS files separately from my dynamic values, which can help a lot with performance too.

    Comments on this post

    • NotionCommotion agrees
    • Nilpo agrees : Absolutely agree.
    Last edited by E-Oreo; November 11th, 2012 at 11:04 AM.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  6. #4
  7. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,650
    Rep Power
    171
    Originally Posted by E-Oreo
    I normally handle this by embedding the dynamic values in my main view, and linking to the main JavaScript externally.

    For example, my main view may look like this:
    Code:
    <script type="text/javascript">
      var value1 = <?php echo json_encode($value1); ?>;
      var value2 = <?php echo json_encode($value2); ?>;
      var value3 = <?php echo json_encode($value3); ?>;
    </script>
    <script type="text/javascript" src="js/jslogic.js"></script>
    Mostly because this method allows the bulk of the JS code to be loaded without the server needing to invoke PHP, which helps a lot with performance. It also allows clients to cache the JS files separately from my dynamic values, which can help a lot with performance too.
    Hello; I didn't know it's allowed to have the javascripts in the main view! Does this mean this code is valid?
    PHP Code:
    <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
                    <title>JS Test</title>
                    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
                    <script type="text/javascript" src="all_javascripts.js"></script>
            </head>
            <body>
                <p id="demo"></p>
                <script type="text/javascript">
                //test.php css hovers
                function change_color(color)
                    {
                     $("p").mouseover(function () {
                            $(this).css("color",color);
                          });
                    }
                //End test.php css hovers
                </script>
                <p class="jquery_box" onmouseover="change_color('<?php echo 'green';?>');"></p>
            </body>
    </html>
    All Javascripts
    Code:
    //////////////////////////////
    //The digital clock
    var myVar=setInterval(function(){myTimer()},1000);
    function myTimer()
    	{
    		var d=new Date();
    		var t=d.toLocaleTimeString();
    		document.getElementById("demo").innerHTML=t;
    	}
    //End the digital clock
    
    
    //////////////////////////////
    //test.php page load report
    $(document).ready(function () {
    	  $(".jquery_box").text("The DOM is now loaded and can be manipulated.");
    	});
    //End test.php page load report
    
    
    //////////////////////////////
  8. #5
  9. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,957
    Rep Power
    1045
    Originally Posted by zxcvbnm
    Hello; I didn't know it's allowed to have the javascripts in the main view! Does this mean this code is valid?
    Ask the W3C: yes. Why do you think it isn't?

    Like I said: It may not be good coding style, but it is valid HTML.

    However, some things look strange. What's the point of

    PHP Code:
    <?php echo 'green' ?>
    And why do you mix jquery with pure JavaScript (document.getElementById etc.)?

IMN logo majestic logo threadwatch logo seochat tools logo