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
Susan SarandonOriginal
2024-12-10 13:57:11372browse

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:

  • 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!

Statement:
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