186

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Razor
  • 2,581
  • 6
  • 21
  • 27
  • 12
    PHP executes on the server. Your click handlers execute on the client. You can't run PHP functions on the click of a button like this. You can do it in Javascript, however. –  Dec 23 '13 at 06:51
  • 4
    Thank you for replying. Could you please tell me how exactly do I call these PHP functions from JavaScript? – Razor Dec 23 '13 at 06:56
  • See [this answer](http://stackoverflow.com/a/20731315/1438393). – Amal Murali Dec 23 '13 at 06:58

13 Answers13

108

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;
    }
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roopendra
  • 7,674
  • 16
  • 65
  • 92
78

Button clicks are client side whereas PHP is executed server side, but you can achieve this by using Ajax:

$('.button').click(function() {
  $.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John" }
  }).done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
});

In your PHP file:

<?php
    function abc($name){
        // Your code here
    }
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Moeed Farooqui
  • 3,604
  • 1
  • 18
  • 23
  • 7
    Thanks for giving the solution. In the AJAX code snippet that you have provided me, how do I call the PHP functions in the .done property? – Razor Dec 23 '13 at 07:08
  • once you use ajax to call the php file, is there any way to call the specific php function? or will I have to put each one in a different file? – Lordbug Apr 20 '17 at 00:01
  • 1
    also use JS preventdefault to prevent form from submitting so the page won't reload. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_preventdefault – csandreas1 Feb 21 '18 at 18:21
  • As a beginner, I want to clear my doubt. Should those pages be prevented from developing where both HTML and PHP codes are merged in a single page with HTML serving the purpose of client interaction like forms and PHP serving as the reply to such HTML forms like printing some results based on whether a button in a form is clicked? – asn Apr 20 '19 at 09:10
  • How is this supposed to work? I've put an echo statement in the abc function body, and I've put breakpoints on both the function declaration line, and on the echo call in the function. When I click the button, the first breakpoint is hit (ie the function is declared) but the one in the body never hits, which I take to mean the function is never called. – Shaggydog Nov 21 '19 at 12:46
  • You can get e.g. the variable "name" from $_POST['name']. The function in the code above isn't called, but the file which it is in, does run. You have to actually call the function from within the file which it is in. – Emil Karlsson Dec 14 '20 at 09:54
62

You should make the button call the same page and in a PHP section check if the button was pressed:

HTML:

<form action="theSamePage.php" method="post">
    <input type="submit" name="someAction" value="GO" />
</form>

PHP:

<?php
    if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
    {
        func();
    }
    function func()
    {
        // do stuff     
    }
?>
DavidS
  • 2,160
  • 1
  • 19
  • 22
20

You cannot call PHP functions like clicking on a button from HTML. Because HTML is on the client side while PHP runs server side.

Either you need to use some Ajax or do it like as in the code snippet below.

<?php
    if ($_GET) {
        if (isset($_GET['insert'])) {
            insert();
        } elseif (isset($_GET['select'])) {
            select();
        }
    }

    function select()
    {
       echo "The select function is called.";
    }

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

You have to post your form data and then check for appropriate button that is clicked.

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
Maz I
  • 3,664
  • 2
  • 23
  • 38
14

To show $message in your input:

<?php
    if(isset($_POST['insert'])){
        $message= "The insert function is called.";
    }
    if(isset($_POST['select'])){
        $message="The select function is called.";
    }
?>


<form  method="post">
    <input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" >
    <input type="submit" name="insert" value="insert">
    <input type="submit" name="select" value="select" >
</form>

To use functioncalling.php as an external file you have to include it somehow in your HTML document.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user5253060
  • 141
  • 1
  • 2
  • Just to elaborate on your answer.. you set the form ```action``` to the PHP file that contains the function. So it will be: ```
    ```
    – Mario Feb 13 '22 at 12:11
  • Any idea how I do this with a woocommerce product page? just outputting the product name and description? – Paul M Apr 22 '22 at 19:04
10

Try this:

if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    insert();
}
alexswear
  • 625
  • 2
  • 9
  • 10
9

You can write like this in JavaScript or jQuery Ajax and call the file

$('#btn').click(function(){
  $.ajax({
    url:'test.php?call=true',
    type:'GET',
    success:function(data){
    body.append(data);
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<form  method='get' >

  <input type="button" id="btn" value="click">
</form>

<?php
    if(isset($_GET['call'])){

        function anyfunction(){
            echo "added";

            // Your funtion code
        }
    }
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vipul Tank
  • 111
  • 1
  • 6
7

The onclick attribute in HTML calls JavaScript functions, not PHP functions.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
linesarefuzzy
  • 1,890
  • 17
  • 17
5

I was stuck in this and I solved it with a hidden field:

<form method="post" action="test.php">
    <input type="hidden" name="ID" value"">
</form>

In value you can add whatever you want to add.

In test.php you can retrieve the value through $_Post[ID].

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sanya Zahid
  • 466
  • 6
  • 18
4

Use a recursive call where the form action calls itself. Then add PHP code in the same form to catch it. In foo.php your form will call foo.php on post

<html>
    <body>
        <form action="foo.php" method="post">

Once the form has been submitted it will call itself (foo.php) and you can catch it via the PHP predefined variable $_SERVER as shown in the code below

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        echo "caught post";
    }
?>
        </form>
    </body>
</html>
Ram
  • 3,092
  • 10
  • 40
  • 56
3

Here is an example which you could use:

<html>
    <body>
        <form action="btnclick.php" method="get">
            <input type="submit" name="on" value="on">
            <input type="submit" name="off" value="off">
        </form>
    </body>
</html>
<?php
    if(isset($_GET['on'])) {
        onFunc();
    }
    if(isset($_GET['off'])) {
        offFunc();
    }

    function onFunc(){
        echo "Button on Clicked";
    }
    function offFunc(){
        echo "Button off clicked";
    }
?>
BaeFell
  • 640
  • 1
  • 8
  • 28
Sagar Mali
  • 54
  • 4
3

Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.

<?php
    if(array_key_exists('button1', $_POST)) { 
        button1(); 
    } 
    else if(array_key_exists('button2', $_POST)) { 
        button2(); 
    } 
    function button1() { 
        echo "This is Button1 that is selected"; 
    } 
    function button2() { 
        echo "This is Button2 that is selected"; 
    } 
?> 

<form method="post"> 
    <input type="submit" name="button1" class="button" value="Button1" /> 
    <input type="submit" name="button2" class="button" value="Button2" /> 
</form> 

source: geeksforgeeks.org

Georgi Georgiev
  • 362
  • 6
  • 9
2

You can simply do this. In php, you can determine button click by use of

if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}

Therefore you should modify you code as follows:


<?php

if(isset($_Post['select']){
 echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
 echo "insert button clicked and insert method should be executed";
}
           
        ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <body>
        <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>

<script>
//This will be processed on the client side
function insert(){
  window.alert("You click insert button");
}

function select(){
  window.alert("You click insert button");
}
</script>
</body>
</html>


        
trustidkid
  • 577
  • 4
  • 6