SarmenHB
SarmenHB

Reputation: 527

how do i write a javascript alert box to give a yes or no question and integrate with php calls?

i am trying to figure out how to create a javascript alert box asking the user if they would like to delete a record (that their viewing) and when the user presses yes a query is called through php to delete a database row. and if the user presses no nothing will happend.

wondering how this can be done

thanks

ps:

this is what i did and it didnt work.

<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) { 
<?php
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>
}
</script>

Upvotes: 0

Views: 6470

Answers (1)

Aistina
Aistina

Reputation: 12683

if (window.confirm("Are you sure?")) {
  // call php code here, either through going to a new page,
  // or by doing an ajax request
}

For your update: The problem is that the PHP code is being executed by the server, which does not run the Javascript, and the Javascript runs at the client side, with no knowledge of the PHP code.

This means the PHP code will always run, simply ignoring the the window.prompt call, as that is not part of PHP. The Javascript that is executed by the client looks simply like this:

<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) { 
}
</script>

Which obviously does nothing, if you were to even reach this page, because you are sending the user to a new page using the Location header.

What you need to do is put the PHP code you wrote on a second page, and take the client to that page, only once the window.confirm() has run. Something like this:

file1.php

<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) {
  document.location = "file2.php?id=<?php echo $_GET['id'] ?>";
}
</script>

file2.php

<?php
$id = $_GET['id'];
if (!is_numeric($id)) $id = -1;
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>

Upvotes: 11

Related Questions