2

I am trying to make a delete button which I'll be able to delete some user from my database but main thing how to call PHP function with clicking on some div etc..

<div class="cross" onclick='<?php deleteUser("Nickname")?>'>X</div>
<?php
function deleteUser($username) {
  //... code
}
?>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
jacobgod
  • 43
  • 3
  • How to call php function with js: https://stackoverflow.com/questions/15757750/how-can-i-call-php-functions-by-javascript – Sumit Wadhwa Oct 03 '20 at 08:51
  • 1
    Does this answer your question? [How can I call PHP functions by JavaScript?](https://stackoverflow.com/questions/15757750/how-can-i-call-php-functions-by-javascript) – caramba Oct 03 '20 at 08:56

2 Answers2

1

Html can't directly call php, it can do a separate call to load the same page, with the action.

<?php
function deleteUser($username){}

if($_GET['action'] == "delete")
{
    deleteUser($_GET['username']);        
}
?>
<a class="cross" href='?action=delete&username=NickName'>X</a>

The reason for this is because PHP runs on the server, BEFORE anything is sent to the browser. So it requires another page load to run the function by clicking something. It is possible to use javascript and AJAX calls to send a call to a php script without reloading the main page. Just look into Jquery's post or ajax features.

0

You cannot call a PHP function that resides on the server by just clicking on a div that exists on the client browser.

You need to trigger a Javascript event (using e.g. jQuery), that will call a function on the server (e.g. through AJAX), that after checking the parameters are correct and the user has the right of calling it will do what you seek.

There are ready-made frameworks that would allow you to do that.

Otherwise (after including jQuery in your HTML page) you can do something like,

 <div class="cross" id="deleteUserButton" data-user="nickname">X</div>

 
 <script type="text/javascript">
     $('#deleteUserButton').on('click', function() {
         let nick = $(this).attr('data-user');
         $.post('/services/delete.php',
         {
              cmd: 'delete',
              user: nick
         }).then( reply => {
              if (reply.status === 'OK') {
                  alert("User deleted");
              }
         });


 <?php
       $cmd = $_POST['cmd'];

       switch($cmd) {
            case 'delete':
                 $user = $_POST['user'];
                 if (deleteUser($user)) {
                     $reply = [ 'status' => 'OK' ];
                 } else {
                     $reply = [ 'status' => 'failure', 'message' => 'Doh!' ];
                 }
                 break;
        ...

        header('Content-Type: application/json;charset=UTF-8');
        print json_encode($reply);
        exit();
LSerni
  • 55,617
  • 10
  • 65
  • 107