Home >Backend Development >PHP Tutorial >How to Use AJAX to Call PHP Functions on Button Clicks?

How to Use AJAX to Call PHP Functions on Button Clicks?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 14:20:16213browse

How to Use AJAX to Call PHP Functions on Button Clicks?

How to Utilize AJAX to Trigger PHP Functions on Button Clicks

In your scenario, you're attempting to execute PHP functions upon button clicks on the 'functioncalling.php' page. However, you're encountering issues with the output being rendered. This is because PHP functions cannot be directly called through HTML form submissions. You need to employ Ajax to bridge the gap.

Revised HTML Markup and jQuery Code

Update your HTML markup as follows:

<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />

Next, add the following jQuery code:

$(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");
    });
  });
});

The 'ajax.php' File

Create an 'ajax.php' file with the following code:

<?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;
    }
?>

Understanding the AJAX Mechanism

When a user clicks on any of the buttons, the jQuery code triggers an AJAX request to 'ajax.php'. The 'action' parameter contains the value of the clicked button ("insert" or "select"). The '.post()' method sends this data to 'ajax.php', which executes the corresponding PHP function based on the 'action' value. The PHP function's output is captured and displayed appropriately in your response div.

The above is the detailed content of How to Use AJAX to Call PHP Functions on Button Clicks?. 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