-4

I am creating a simple discussion forum, where users can create posts, reply to posts, delete posts, etc. I am having some trouble with deleting posts. I can write the PHP to delete the posts fine, but at the moment the post is instantly deleted (so if someone clicks accidently they have no opportunity to cancel). What I want to do is call a JavaScript function to display a confirm box from PHP, then if the function returns true delete the post, otherwise do nothing. In pseudocode, what I want to do is:

<?php

function display_javascript_confirm_box()
{
if(call_javascript_function()==true)
{
delete();//call PHP function to delete post
}
else
{
return false;
//do nothing
} 
}
?>
Keshava GN
  • 4,195
  • 2
  • 36
  • 47
imulsion
  • 8,820
  • 20
  • 54
  • 84
  • 1
    You have it backwards. Javascript will need to trigger a confirmation and afterwards a new HTTP request if affirmative. See [Reference: Why does the PHP code in my Javascript not work?](http://stackoverflow.com/questions/13840429/reference-why-does-the-php-code-in-my-javascript-not-work) – deceze Apr 18 '13 at 09:41
  • lacks research effort. this is a VERY common question. – STT LCU Apr 18 '13 at 09:42

5 Answers5

2

You simply need this

<input type="submit" value="Delete" onclick="return confirm('Your Message');" />

Demo

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
2

The easiest way is to do otherwise: confirm via js, and delete via php )

<a href="/path/to/delete" onclick="return confirm('Do you really want to delete?');">delete</a>

Link will be folowed only if user confirms ok in dialog box.

Roman Usachev
  • 296
  • 2
  • 4
1

It is impossible to call a javascript function from PHP. Note that PHP is running on server while javascript is running in the client - the browser

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Display the confirm box with Javascript, not with PHP. So after it's confirmed, the value of the posted button will be sent to PHP, then you can catch it by isset() and afterwards trigger delete()

Royal Bg
  • 6,988
  • 1
  • 18
  • 24
0

you should understand that JavaScript runs on a client side (Browser) and PHO on the Server side - if you wants to run some PHP code from javaScript you should establish connection to server. For example using AJAX.

Ilya
  • 169
  • 6