SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Apr 2005
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    use a constant defined in PHP inside javascript

    How to use a constant defined in PHP inside javascript?

    e.g. after I define this PHP constant,
    define ('COUNT_MAX', 10);

    I want to do something like this in javascript:
    if (time < COUNT_MAX)

  2. #2
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You cannot directly access the php variables from javascript. However if you use php to print out the javascript you can include the php variable in the javascript to be printed out.
    Such as:
    PHP Code:
    <?
    $foo 
    'bar';
    print <<<block
    <script type="text/javascript">
     alert ('
    $foo');
    </script>
    block;
    ?>

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,810
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    You can have PHP parsed in external Javascript using:

    <script type="text" src="myjs.php"></script>

    Any PHP in myjs.php will be processed on the server and the result will then be delivered to the browser to run as Javascript.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How to use a constant defined in PHP inside javascript?
    1) Browser requests page from server.
    2) Before server sends the page to the browser, if the page has a certain extension, like .php, the server sends the page to the php engine to execute any php code.
    3) Server sends page to the browser. The page contains html and js.
    4) Browser executes js and displays html.

    So, when the page arrives in the browser, there is no such thing as a php constant or a php anything.


Bookmarks

Posting Permissions

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