Home > Back-end >  call a php function with onclick
call a php function with onclick

Time:03-06

how do you call a php function with html I have this:

<input   type="button" name="woonkameruit" value="UIT" onclick="kameroff('woonkamer');<?php woonkameruit()?>">

and

function woonkameruit() {
   exec("sudo pkill python");
   exec("sudo python3/home/pi/Documents/Programmas/WOONKAMERUit.py");
}

can you help?

CodePudding user response:

You cannot directly call PHP functions with HTML as it is in the backend.

However you can send a request to the backend with JS or HTML and make the PHP handle it so it executes a function.

To do this there are multiple ways:

HTML: Form

JS: Ajax

If you do not know how to implement this I suggest going to websites such as w3schools or just looking in youtube.

CodePudding user response:

You have to send the function name via Javascript, and create some controller like logic. It is a similar to what Laravel Livewire does. For Example:

frontend.php:

<!-- Frontend Logic -->
<input id="myButton"   type="button" name="woonkameruit" value="UIT">


<!-- Put Before </body> -->
<script type="text/javascript">

function callBackend(f) {
    fetch(`https://myapp.com/backend.php?f=${f}`)
        .then(response => response.json())
        .then(data => {
            // Do what you have to do with response
            console.log(data)

            if(data.success) {
                // Function Run Successfully
            } else {
                // Function Error
            }
        
        })
        // Other Errors
        .catch(err => console.error(err));
}

const myButton = document.getElementById('myButton')

myButton.onclick = (e) => {
   e.preventDefault()

   callBackend('woonkameruit')
}

</script>

backend.php:

<?php
// Backend logic

function send_json_to_client($status, $data) {
    $cors = "https://myapp.com";
    header("Access-Control-Allow-Origin: $cors");
    header('Content-Type: application/json; charset=utf-8');
    http_response_code($status);
    echo json_encode($data);
    
    exit(1);
}

function woonkameruit() {
    $first_command  = exec("sudo pkill python");
    $second_command = exec("sudo python3/home/pi/Documents/Programmas/WOONKAMERUit.py");

    $success = false;
    $message = 'Something Went Wrong';
    $status = 500;

    // If everything went good. Put here your success logic
    if($first_command !== false && $second_command !== false) {
        $success = true;
        $message = 'Everything Is Good';
        $status = 200;
    }

    return [
        'status' => $status,
    
        'response' => [
            'success' => $success,
            'message' => $message,
        ],
    ];
 }

$authorizedFunctions = [
    'woonkameruit'
];

if(isset($_GET['f'])) {

    $fn = filter_input(INPUT_GET, 'f', FILTER_SANITIZE_STRING);

    if( in_array( $fn, $authorizedFunctions ) ) {

        $response = $fn();

        send_json_to_client($response['status'], $response['response']);

    } else {
        send_json_to_client(403, [
            'success' => false,
            'message' => 'Unauthorized'
        ]);
    }

} else {
    send_json_to_client(404, [
        'success' => false,
        'message' => 'Not Found'
    ]);
}
  • Related