development

버튼 클릭으로 PHP 함수를 호출하는 방법

big-blog 2020. 6. 27. 10:11
반응형

버튼 클릭으로 PHP 함수를 호출하는 방법


SubmitInsert 두 개의 버튼이 포함 된 functioncalling.php 페이지를 만들었습니다 . PHP 초보자는 버튼을 클릭했을 때 어떤 기능이 실행되는지 테스트하고 싶습니다. 출력이 같은 페이지에 오기를 원합니다. 그래서 각 버튼마다 하나씩 두 가지 기능을 만들었습니다. functioncalling.php의 소스 코드는 다음과 같습니다.

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

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

여기서 문제는 버튼을 클릭 한 후에도 출력이 없다는 것입니다.

내가 정확히 어디로 잘못 가고 있습니까?


버튼 클릭은 클라이언트 측 이지만 PHP는 서버 측 에서 실행 되지만 Ajax 를 사용하여이를 수행 할 수 있습니다 .

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

PHP 파일에서 :

<?php
    function abc($name){
        // Your code here
    }
?>

예, 여기에 Ajax가 필요합니다. 자세한 내용은 아래 코드를 참조하십시오.

 

이렇게 마크 업을 변경하십시오

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

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

버튼을 같은 페이지와 PHP 섹션에서 버튼을 눌렀는지 확인해야합니다.

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

HTML에서 버튼을 클릭하는 것과 같은 PHP 함수를 호출 할 수 없습니다. PHP는 서버 쪽을 실행하는 동안 HTML은 클라이언트쪽에 있기 때문입니다.

Ajax를 사용해야하거나 아래 코드 스 니펫과 같이하십시오.

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

양식 데이터를 게시 한 다음 클릭 한 적절한 버튼을 확인해야합니다.


입력에 $ message를 표시하려면 다음을 수행하십시오.

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

functioncalling.php를 외부 파일로 사용하려면 HTML 문서에 어떻게 든 포함시켜야합니다.


이 시도:

if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    insert();
}

JavaScript 또는 jQuery Ajax로 이와 같이 작성하고 파일을 호출 할 수 있습니다

$('#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
        }
    }
?>


onclickHTML 속성은 PHP 함수가 아닌 JavaScript 함수를 호출합니다.


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>

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].


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

참고URL : https://stackoverflow.com/questions/20738329/how-to-call-a-php-function-on-the-click-of-a-button

반응형