July 10, 2011

How to use a php code in javascript

Question by Javad Yousefi

I want to use php code in javascrip ,but it dosn’t work:

        <script type="text/javascript">
        function edit(pollNo)
        {
            <?php
                $result = mysql_query( 'CALL ret_poll('.pollNo.')' );
                $row = mysql_fetch_assoc($result);
                echo 'document.poll.pollTitle.value='.$row['title'];
            ?>

        }
    </script>

Answer by Starx

Javed, its not that you can’t use php in javascript. However the uses are very limited.

See an example

alert('<?php echo "hi"; ?>');

Once the server renders this, the script will be

`alert('hi');` //SO it will alert `hi` now

Mostly, you can use PHP and javascript mixture to create a script you want to run on the run time

For example

<script>
   <?php
   $location = $_SESSION['logged'] ? 'admin.php' : 'index.php';
   ?>
   window.location('<?php echo $location; ?>');
</script>

Or Something like this

<script>
    <?PHP if($test==true) { ?>
        function test() {
            //do something;
        }
    <?php } else { ?>
        function test() {
            //do something else but not the previous one
        }
    <?php } ?>
</script>

However, What you are trying is TRYING TO USE PHP CODES AS JAVASCRIPT Which is not possible !!!!!!!!

Instead, you can use AJAX, as other answers suggest, for a workaround.

A little demo of your probable solution is

FILE: myMYSQLPROCESSING.php

        // Your connections and other above                
        $result = mysql_query( 'CALL ret_poll('.$_POST['pollno'].')' );
        $row = mysql_fetch_assoc($result);
        echo $row['title'];

JS

    function edit(pollNo)
    {
        $.post("myMYSQLPROCESSING.php",
            { "pollno" : pollNo },
            function(data) {
                // Now data, will contain whatever you echo in myMYSQLPROCESSING.php
                // May be a success message or error message

                // and do whatever you want with the response

               document.poll.pollTitle.value=data; //in your case something like this
            }
        );
    }

This is a jQuery code, if you are not familiar with it.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!