Search code examples
phpjavascriptdrupal-6

How do I call a php function from javascript onclick() event?


For example, I have a php function:

function DeleteItem($item_id)
{
     db_query("DELETE FROM {items} WHERE id=$item_id");
}

Then, I have something like the following:

<html>
<head>
<script type="text/javascript">
function DeleteItem($item_id)
{
     alert("You have deleted item #"+$item_id);
}
</script>
</head>

<body>
<form>
Item 1
<input type="button" value="Delete" onclick="DeleteItem(1)" />
</form>
</body>
</html>

I want to be able to call the PHP function DeleteItem() from the javascript function DeleteItem() so that I can use Drupal's db_query() function, so I don't have to try to establish a connection to the database from javascript.

Does anyone have any suggestions on how this might be done? P.S. I understand that PHP processes on the server-side and javascript processes on the client-side, so please no responses saying that. There has got to be some kind of trick one can do in order to have this work out. Or maybe there is a better way of doing what I am trying to accomplish.


Solution

  • Since you are aware that PHP processes on the server-side and javascript processes on the client-side, you must also realize you can't call a PHP "function" from javascript. Your client side code can redirect to a PHP page, or invoke a PHP program using AJAX. That page or program must be on the server and it should do a lot more than just the one line you have in your function. It should also check for authentication, authorization, etc. You don't want just any client side script anywhere to call your PHP.