0

For instance I have a php function

<?php
   function SayHi($msg){
       return $msg;
   }
?>

The following part triggers the onclick event

<a href="" onclick="">Click</a>

How can I merge the two such that when I click on Click, the php function is invoked..?

3
  • 1
    Please put your code in a code block... Commented Sep 28, 2011 at 12:08
  • 1
    You're confusing two languages. PHP does not have an onclick event. Javascript does. By the time your web page is in your browser, PHP is done and no longer accessible from the page. Commented Sep 28, 2011 at 12:12
  • You need to modify the browser to get this to work. Basically the browser must support PHP in <script> tags to achieve that. Commented Sep 28, 2011 at 12:35

5 Answers 5

8

You can not. PHP is executed serverside, while javascript is executed clientside.

THe generic solution for this is to use asynchronous Javascript (ajax) to call on your webserver, which in turn can invoke PHP code to do various things.

jQuery is a very nice library to handle this, and much more.

Sign up to request clarification or add additional context in comments.

Comments

5

There are many ways to do this, most are complicated.

One easier way is:

<?php
    function myFunc() { die('yay'); }
    if (isset($_REQUEST['myButton'])) myFunc();
?>
<form><button name="myButton">Click Me</button></form>

Comments

4

Whaaat? PHP is server-side you cannot invoke a php function from javascript. However you can do this with ajax.

AJAX

Comments

3

You'll want to use AJAX. You need to call a server-side resource from the JavaScript code, and jQuery has a very handy function for making the call to the server. But making the call from the JavaScript is only half the story, you'll also need something on the server listening for that call. It would essentially be another PHP script which acts as a page in and of itself, but would return data in the form of (most likely) JSON instead of HTML. It's not meant to be human-readable, but rather to be a sort of web service for your JavaScript code to use.

You can find a simple example here.

Comments

2

please get involved with the basics of PHP: http://tut.php-quake.net/en/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.