Executing PHP Functions on Button Click
You have created a PHP page with two buttons intended to call specific functions, but you're not getting the expected output. The issue lies in the approach you're using.
To correctly execute a PHP function when a button is clicked, you need to utilize Ajax for asynchronous communication between the page and the server. Here's a modified version of your code that incorporates Ajax:
Modified Markup:
<input type="submit" class="button" name="insert" value="insert" /> <input type="submit" class="button" name="select" value="select" />
jQuery:
$(document).ready(function() { $('.button').click(function() { var clickBtnValue = $(this).val(); var ajaxurl = 'ajax.php', data = {'action': clickBtnValue}; $.post(ajaxurl, data, function(response) { // Response div goes here. alert("action performed successfully"); }); }); });
ajax.php:
<?php 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; } ?>
Explanation:
With this approach, when you click on either the "Insert" or "Select" button, the corresponding function will be executed, and you will see an alert message indicating the successful execution.
The above is the detailed content of How Can I Execute PHP Functions with Button Clicks Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!