Imri Persiado Imri Persiado - 5 months ago 12
PHP Question

Using a php function inside javascript code

I would like to run a php function from a javascript code, to be more specific I got a button that delete a record from the database. The function that does that named

delete_post($id)


Here is what I tried:

<input type="submit" name="delete" value="delete"
onClick="if(confirm('Are you sure?')) {<?php delete_post($row['id']);?>}">


When I click the button, there is no alert box. The funny thing is if I don't call a function inside the php code and I do something else such as echo the alert does pop out but the php code doesn't executed.

So, how can I do that? How can I run a php code inside my javascript onClick code.

Answer

You can't. PHP is supposed to be run before the page loads, thus giving it the name Pre-Hypertext Protocol. If you want to run PHP after a page loads via JavaScript, the best approach would be linking to a new page that runs the PHP, then returning the user back.

file1.php:

...
<input type="submit" name="delete" value="delete" onClick="if(confirm('Are you sure?')) document.location.href='file2.php';">
...

file2.php:

<!doctype html>
<html>
<head>
<?php
delete_post($row['id']);
?>
<meta http-equiv="refresh" content="0; url=file1.php" />
</head>
<body>
<p>You will be redirected soon; please wait. If you are not automatically redirected, <a href="file1.php">click here</a>.</p>
</body>
</html>

Assuming you would have multiple IDs, you can keep them all onto one redirect page:

if(confirm('Are you sure?')) document.location='file2.php?id=2'; // file1.php
delete_post($row[$_GET["id"]]); // file2.php

But do not put PHP code directly into the query string, or your site could be susceptible to PHP injection