简体   繁体   中英

How do I trigger a php function on onclick event?

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..?

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.

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>

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

AJAX

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 .

请参与PHP的基础知识: http//tut.php-quake.net/en/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM