tags:

views:

34

answers:

2

In PHP,

I want to execute a function when a hyperlink is clicked. The only way I can think of doing this is by having the link attach a get parameter to the url when clicked and by doing an if statement that checks to see if that parameter exists and if so then have the function executed. But is there a way to do this like:

<a href='#' onclick='<?php functionName(); ?>'>

Obviously there are a million things wrong with this example but is it possible in any other way?

+6  A: 

PHP is executed on the server side so, no, you can't. You'll either need to use JavaScript to perform the function or use Ajax to contact the server and retrieve the results of a PHP script.

John Conde
A: 

Well technically you can't but here is a trick to make it work. You just need to dynamiclly create your javascript. The drawback to this is you can't pass any parameters but it can be convenient at times.

However unless you understand what is going on you will get in to problems. Make sure you understand Johns answer before proceeding.

Observe:

<a href=# onclick="jsPhpFunction();">

<script>
function jsPhpFunction()
{
   <?php
        $name = query("Select name from table where id = ? ", $_REQUEST[id]);
        echo "window.alert('Hello {$name}');";
    ?>
}
</script>
Byron Whitlock
makes sense, I kinda had that in mind but thought there might be a more direct way and this of course won't work if js is turned off. Thanks, will do it this way anyway.
Tim