1
    <html>
    <head>

    <script type="text/javascript">
    var t;
 alert(t);
    </script>

    </head>

    <body>

    <?php

    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'pass';

    $t_id = 6;

    $con = new PDO("mysql:host=$dbhost;dbname=testing",$dbuser,$dbpass);               

    $q = $con-> prepare("query");

    $q -> bindParam(1,$t_id);

    $q -> execute();
    $res = $q->fetchAll();

    foreach($res as $r)
    {
            $ab = $r[0];
        $abc = $r[1];
    }          
     echo $ab;
     echo $abc;  
    ?>
    <script type="text/javascript">
    t = <?php echo $abc;?>;

    </script>
    </body>
    </html>

When i alert "t" variable just after assigning php variable, it works fine. But i want to use "t" in the head section of the page. actually i just want to set JS variable from DB. how to do it?

4 Answers 4

3

hope it helps you,

<script type="text/javascript">
    var t = "<?php echo $abc;?>"; //if not initialised variable t before use var
</script>
1

Try like

<script type="text/javascript">
    t = '<?php echo $abc;?>';
</script>
1

I'd suggest that you put the php-code before any html output as the first part of your file. As soon as one html character is transferred, the complete header of the document is sent and you will not be able to change header-information any more.

To output a php-variable to javascript, use the following code if $abc is a string:

<script type="text/javascript">
    "use strict";
    var t = '<?php echo $abc; ?>';
    alert(t);
</script>

and the following if $abc is a numeric value:

<script type="text/javascript">
    "use strict";
    var t = <?php echo $abc; ?>;
    alert(t);
</script>

I strongly recommend using the

"use strict";

line. It will give you better debug output during development. For example it will tell you if you are assigning a value to a variable that has not been initiated. Helps a lot, trust me ;-).

0
 <html>
    <head>
//move your php code to head of the page
    <?php

    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'pass';

    $t_id = 6;

    $con = new PDO("mysql:host=$dbhost;dbname=testing",$dbuser,$dbpass);               

    $q = $con-> prepare("query");

    $q -> bindParam(1,$t_id);

    $q -> execute();
    $res = $q->fetchAll();

    foreach($res as $r)
    {
            $ab = $r[0];
        $abc = $r[1];
    }          
     echo $ab;
     echo $abc;  
    ?>

    <script type="text/javascript">
       var t;
       t = <?php echo $abc;?>; //add the database variable here you want to use      
       alert(t);
    </script>

    </head>
    <body>       

    </body>
    </html>

Let us know if its still confusing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.