How to call a PHP function on the click of a button

Razor picture Razor · Dec 23, 2013 · Viewed 1.1M times · Source

I have created a page called functioncalling.php that contains two buttons, Submit and Insert.

I want to test which function is executed when a button gets clicked. I want the output to appear on the same page. So, I created two functions, one for each button.

<form action="functioncalling.php">
    <input type="text" name="txt" />
    <input type="submit" name="insert" value="insert" onclick="insert()" />
    <input type="submit" name="select" value="select" onclick="select()" />
</form>

<?php
    function select(){
        echo "The select function is called.";
    }
    function insert(){
        echo "The insert function is called.";
    }
?>

The problem here is that I don't get any output after any of the buttons are clicked.

Where exactly am I going wrong?

Answer

Roopendra picture Roopendra · Dec 23, 2013

Yes, you need Ajax here. Please refer to the code below for more details.

 

Change your markup like this

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

 

jQuery:

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

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