Javascript Confirm Delete in One PHP File (on href)
Asked Answered
C

3

5
<p><span class="linky"><a href="deletephone.php?id=' . $row['id'] . '">Delete Phone</a></span></p><br />

I have the above code that I am using to link to a delete script. I want to somehow incorporate Javascript with a simple onclick confirmation. This way if they choose OK, I can run the code to delete the item from the database, but if they choose Cancel then I can cancel the operation and do nothing.

I have tried a whole variety of functions with changing the window.location to the delete file, and trying to cancel the href= if they choose Cancel, but it always goes to the link regardless of what the user clicks.

I would like to be able to keep the delete functions inside the same PHP file if possible, but this is not necessary at all.

Thanks in advance!

ASIDE: If there is a simple PHP way to check IF the alert was confirmed or denied, that could work also. Any way to check what the user chooses and then run my simple delete PHP command.

Curable answered 19/4, 2010 at 5:59 Comment(0)
S
12

If you just want a simple confirmation:

<a href="deletephone.php?id=' . $row['id'] . '" onclick="return confirm(\'Really delete?\');">Delete Phone</a>

confirm prompts the user and returns true if they say OK, false if they say Cancel.

Slipknot answered 19/4, 2010 at 6:5 Comment(2)
Thank you for escaping the apostrophes. Answer worked perfectly. For some reason a similiar function did not work for me.Curable
@gamerzfuse: Glad that worked! It's easy to forget the return, maybe that was what wasn't working before, who knows.Slipknot
S
4

You can set the onclick attribute of the link. If the function returns false, the link will not proceed.

<a href="deletephone.php?id=' . $row['id'] . '" onclick="return confirm('Are you sure?');">Delete Phone</a>

Here, the confirm() function will return true if the user pressed OK, and false if the user pressed Cancel.

Sisyphean answered 19/4, 2010 at 6:4 Comment(0)
S
0

Just use this code

<a href="deletephone.php?id='. $row['id'].'" onclick="return confirm('Are you sure to delete this ?');">Delete Data</a>
Strader answered 28/2, 2014 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.