Home >Web Front-end >JS Tutorial >How to Execute PHP Functions from Onclick Events?
Original Question:
Can I call a PHP function only when an anchor tag is clicked?
PHP and HTML Code Provided:
<code class="php">function removeday() { /* Code here */ }</code>
<code class="html"><a href="" onclick="removeday()" class="deletebtn">Delete</a></code>
Understanding the Language Interplay
To clarify, PHP and JavaScript are distinct languages with specific roles:
Executing PHP Functions from Onclick
As mentioned, PHP doesn't execute based on onclick events. To do this, we must use a server request (for example, a GET request using a query string parameter):
<code class="php"><!DOCTYPE HTML> <html> <?php function runMyFunction() { echo 'I just ran a php function'; } if (isset($_GET['hello'])) { runMyFunction(); } ?> Hello there! <a href='index.php?hello=true'>Run PHP Function</a> </html></code>
Alternative: Asynchronous JavaScript and XML (AJAX)
To avoid refreshing the page when calling PHP functions, AJAX can be employed. This allows for requests to PHP without page reloads. Search "jQuery AJAX" for implementation details.
Recommendation for Newcomers
Consider using Laravel to establish a solid foundation in this area: http://laravel.com/.
The above is the detailed content of How to Execute PHP Functions from Onclick Events?. For more information, please follow other related articles on the PHP Chinese website!