Can I use a php variable in a javascript function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpuser123
    New Member
    • Dec 2009
    • 108

    Can I use a php variable in a javascript function?

    I want to use a php variable in my javascript.
    Code:
    <script type='text/javascript'>
    function display_alert(x){
    alert(x);
    }
    </script>
    <body>
    <?php $var1='phpvariable';
    
    echo "<button onclick='display_alert($var1)'>Diaplay alert</button>";
    ?>
    </body>
    I am not able to execute such a script..
    I need to pass a php variable to a javascript function .Is that possible ?
    If so,hw cn i implement this?
    Thanks in adv
    With regards
    phpuser123
    Last edited by Dormilich; Apr 13 '10, 08:09 PM. Reason: Please use [code] tags when posting code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    you need to pass the variable as JavaScript string, that is, surrounded by " (or ')

    Comment

    • phpuser123
      New Member
      • Dec 2009
      • 108

      #3
      I passed the variable within quotes as u mentioned..I got $var1 instead of phpvariable ...

      Code:
      <script type='text/javascript'>
         function display_alert(x){
        alert(x);
        }
        </script>
        <body>
        <?php $var1='phpvariable';
       $var2='display_alert("$var1")';
      
       echo "<button onclick=$var2>Display alert</button>";
       ?>
       </body>
      Is that what u exactly u mean ?
      To some extent it worked bt I gt the name of my variable instead of the value it holds..
      Last edited by Dormilich; Apr 15 '10, 05:57 AM. Reason: Please use [code] tags when posting code

      Comment

      • chathura86
        New Member
        • May 2007
        • 227

        #4
        Code:
        <script type='text/javascript'>
        function display_alert(x)
        {
        	alert(x);
        }
        </script>
        <body>
        <?php 
        
        $var1='phpvariable';
        $var2='display_alert("' . $var1 . '")';
        
        echo "<button onclick=$var2>Display alert</button>";
        ?>
        </body>
        try this

        Regards

        Comment

        • phpuser123
          New Member
          • Dec 2009
          • 108

          #5
          Originally posted by chathura86
          Code:
          <script type='text/javascript'>
          function display_alert(x)
          {
          	alert(x);
          }
          </script>
          <body>
          <?php 
          
          $var1='phpvariable';
          $var2='display_alert("' . $var1 . '")';
          
          echo "<button onclick=$var2>Display alert</button>";
          ?>
          </body>
          try this

          Regards
          Thanks that worked out..

          Comment

          Working...