Home > Backend Development > PHP Tutorial > How Can I Execute PHP Functions with a Button Click Using AJAX?

How Can I Execute PHP Functions with a Button Click Using AJAX?

Susan Sarandon
Release: 2024-12-10 13:57:11
Original
378 people have browsed it

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">
Copy after login

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");
        });
    });
});
Copy after login

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;
}
?>
Copy after login

Explanation:

  • The revised button markup adds a class "button" to both buttons, making them compatible with jQuery.
  • The jQuery code triggers an Ajax call when any button with the class "button" is clicked.
  • The Ajax request sends the clicked button's value to the ajax.php file.
  • In ajax.php, we process the action based on the received value. It invokes the corresponding insert() or select() function, prints the output, and exits the script.
  • When the Ajax call is successful, the response from ajax.php is discarded, and an alert message is displayed on the calling page.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template