简体   繁体   中英

how to call a php function on button click

These are two files

Calling.php

<html>
<body>
<form action="Called.php" method="get">
    <input type="button" name="B1" value="B1">
    <input type="button" name="B2" value="B2">
    <input type="Submit" name="Submit1"/>

    <!-- <a href="http://www.google.com?act=google">Google</a>
    <a href="http://www.yahoo.com?act=yahoo">yahoo</a>
     -->
</form>     
</body>
</html>

And Called.php

<?php
if(isset($_GET("Submit1")))
{   
        echo("<script>location.href = 'http://stackoverflow.com';</script>");
}
if(isset($_GET["B1"]))
{
    echo("<script>location.href = 'http://google.com/';</script>");
    exit();
} 
if(isset($_GET["B2"]))

 - List item

{
    echo "<meta http-equiv='refresh' content='0;url=http://www.yahoo.com'>";
    exit(); 
}
?>

When i click the buttons "B1" and "B2", page will blink but now where redirect and third one "Submit" button will redirect to new page and there i am getting the out put as "Called.php".

Please spend few seconds for this php beginner.

You can't directly because the button click is a client side activity and PHP is server side. If you make all the inputs submit then the one the user clicked will be submitted as part of the $_GET array but that only works if the user clicks one of them and doesn't submit the form by, say, hitting Enter in a text input.

You could attach AJAX events to the button and have them trigger off a PHP script to run the function you want to run, but that has its own set of issues.

EDIT: I should note that your method of redirecting is rather inelegant to say the least. You can just use header() to do the redirection, it would be much cleaner than all this messing around with echoing out javascript.

You need to use Ajax to do this. If you are using jQuery ajax the code will look something like this

$(function(){
   $('input[type="button"]').click(function(){
        var name = $(this).attr('value');
        $.ajax({
            type :'GET',
            url  : 'Calling.php',
            data :{name:name}
            success : function(data) {
              //do smthng 
           }
        })
   })
})

//Code is not tested. Need to verify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM