Home >Backend Development >PHP Tutorial >How Can I Execute PHP Functions with a Button Click Using AJAX?
Call PHP Functions on Button Click
To call a PHP function when a button is clicked, we need to utilize Ajax, as evident in the following solution:
Revised Markup:
Update the button markup as follows:
<input type="submit">
jQuery:
$(document).ready(function() { $('.button').click(function() { var clickBtnValue = $(this).val(); var ajaxurl = 'ajax.php'; var 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:
Note that this technique is asynchronous. After the button is clicked, the Ajax request is sent in the background, and the action is only performed when the response from the server is received.
The above is the detailed content of How Can I Execute PHP Functions with a Button Click Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!