user1903239
user1903239

Reputation: 19

JavaScript confirm box not working in php

echo"<td> <a href ='del.php?id=$id' onclick='return confirm('Are you sure?');'><center>Delete</center></a></td>";

i want a prompt msg as the user will click on "delete" if he/she will press "ok" then it will redirect to a page where the data will get deleted and if he/she will press "cancel" then nothing will happen. by using the above code i m not able to get my prompt box nd data is directly getting deleted.

Upvotes: 1

Views: 1951

Answers (4)

user1844626
user1844626

Reputation: 1858

echo"<td><a href ='del.php?id=$id' onclick=\"return confirm('Are you sure?');\"><center>Delete</center></a></td>";

You missed double quotation onclick=\" \";

your confirm box wasn't detected by the program because of single quotations >> onclick='return confirm('Are you sure?');'

Upvotes: 0

vusan
vusan

Reputation: 5331

To remove the complexity you can code as:

$confirm="return confirm('Are you sure?');";
echo "<td> <a href ='del.php?id=$id' onclick='$confirm'><center>Delete</center></a></td>";

OR

echo "<script> function isConfirm() { if(!confirm('Are you sure?')) return false;}";
echo "<td> <a href ='del.php?id=$id' onclick='return isConfirm()'><center>Delete</center></a></td>";

Upvotes: 0

Mathias Schwarz
Mathias Schwarz

Reputation: 7197

This is unrelated to PHP. The onclick handler of an a tag will not stop the browser from changing location. You could do something like this instead:

echo"<td> <a href='javascript:void' onclick='if (confirm(\"Are you sure?\")) window.location=\"del.php?id=$id\";'><center>Delete</center></a></td>";

Upvotes: 0

Sirko
Sirko

Reputation: 74036

You're mixing up ' and " here.

echo "<td> <a href ='del.php?id=$id' onclick='return confirm(\"Are you sure?\");'><center>Delete</center></a></td>";

Your code would have outputted this:

<td> 
  <a href ='del.php?id=123' onclick='return confirm('Are you sure?');'><center>Delete</center></a>
</td>

Even from SOs syntax highlighting you can see, that there is something wrong in the onclick handler. There you have ' inside of other '. So at that point you should replace the inner ' with ". To do so in PHP (where you have surrounding " as well), just escape the inner " by using \" instead.

Upvotes: 5

Related Questions