How can you use php in a javascript function

fosho picture fosho · Dec 12, 2011 · Viewed 163.2k times · Source
<html>
    <?php
        $num = 1;
        echo $num;
    ?>
    <input type="button"
           name="lol" 
           value="Click to increment"
           onclick="Inc()" />
    <br>
    <script>
        function Inc()
        {
        <?php
            $num = 2;
            echo $num;
        ?>
        }
    </script>
</html>

This is what i have so far, not working though, i think i need to use ajax or something but i have no idea what to do.

Thanks

Answer

Andreas Eriksson picture Andreas Eriksson · Dec 12, 2011

You can't run PHP code with Javascript. When the user recieves the page, the server will have evaluated and run all PHP code, and taken it out. So for example, this will work:

alert( <?php echo "\"Hello\""; ?> );

Because server will have evaluated it to this:

alert("Hello");

However, you can't perform any operations in PHP with it.

This:

function Inc()
{
<?php
$num = 2;
echo $num;
?>
}

Will simply have been evaluated to this:

function Inc()
{
    2
}

If you wan't to call a PHP script, you'll have to call a different page which returns a value from a set of parameters.

This, for example, will work:

script.php

$num = $_POST["num"];
echo $num * 2;

Javascript(jQuery) (on another page):

$.post('script.php', { num: 5 }, function(result) { 
   alert(result); 
});

This should alert 10.

Good luck!

Edit: Just incrementing a number on the page can be done easily in jQuery like this: http://jsfiddle.net/puVPc/