Home > Backend Development > PHP Tutorial > How to Execute PHP Functions with AJAX on Button Click?

How to Execute PHP Functions with AJAX on Button Click?

Linda Hamilton
Release: 2024-12-04 19:20:12
Original
300 people have browsed it

How to Execute PHP Functions with AJAX on Button Click?

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

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

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

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!

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