Executing PHP Functions upon Button Click
When constructing forms with buttons, it's often desirable to trigger specific PHP functions when a button is clicked. This allows for custom actions to be taken based on user input. However, a common issue encountered is the absence of output after button clicks.
To resolve this, consider utilizing the following approach:
Button Markup Modification:
Add class names to your submit buttons:
<input type="submit">
jQuery Script:
Bind a click event handler to the buttons:
$(document).ready(function(){ $('.button').click(function(){ var action = $(this).val(); // Get the button's value (insert/select) $.post('ajax.php', { action: action }, function(response) { // Handle the server response here (e.g., display an alert) }); }); });
ajax.php File:
In the 'ajax.php' file, use a switch statement to determine which function to execute based on the 'action' parameter received from the jQuery script:
if (isset($_POST['action'])) { switch ($_POST['action']) { case 'insert': insert(); break; case 'select': select(); break; } } function select() { echo "The select function is called."; exit; } function insert() { echo "The insert function is called."; exit; }
Upon executing this code, clicking the "Insert" or "Select" buttons will trigger the respective functions, displaying the appropriate messages on the page.
The above is the detailed content of How to Execute PHP Functions with AJAX on Button Click?. For more information, please follow other related articles on the PHP Chinese website!