Imri Persiado Imri Persiado - 10 months ago 30
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


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.


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.


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


<!doctype html>
<meta http-equiv="refresh" content="0; url=file1.php" />
<p>You will be redirected soon; please wait. If you are not automatically redirected, <a href="file1.php">click here</a>.</p>

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