SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP to set JS variable outside of JS file

    All my JavaScript is usually unobtrusive, however I need PHP to set a simple JavaScript value:
    Code:
    the_value = 1;
    (it has to be set by PHP depending on some calculations)

    How is the best way to do this as I don;t like the below method?
    Code:
    <script>
    the_value = "<?php echo $the_value; ?>";
    </script>
    I have heard of setting the value in a hidden text field, but I like the idea of setting something like this:
    Code:
    <meta id="the_value" content="1">
    ...where I can then use the unobtrusive JS to grab the value.

    Is that possible?

    What is the best way to do this?

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by johnsmith153 View Post
    I have heard of setting the value in a hidden text field, but I like the idea of setting something like this:
    Code:
    <meta id="the_value" content="1">
    ...where I can then use the unobtrusive JS to grab the value.

    Is that possible?

    What is the best way to do this?
    You can access the value with the expression:
    Code:
    var myVar = Number( document.getElementById( 'the_value' ).content );
    Tab-indentation is a crime against humanity.

  3. #3
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great. Thanks.

    So is doing it with:
    Code:
    <meta id="the_value" content="1">
    the best way to do it, or would there be a better way?

    Thanks

  4. #4
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,313
    Mentioned
    19 Post(s)
    Tagged
    1 Thread(s)
    What was the problem with just...

    the_value = "<?php echo $the_value; ?>";


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
  •