tags:

views:

255

answers:

3

i'm reposting this post i just posted a while ago. http://stackoverflow.com/questions/1035266/how-do-i-write-a-javascript-alert-box-to-give-a-yes-or-no-question-and-integrate/1035285#1035285

i wasnt getting anymore responses so i figured the post got lost in somewhere out there. what i tried doing was this

<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>

and it didnt work. the record just got deleted once i pressed the link to delete. what am i doing wrong? thanks

ps: i cant do ajax yet im looking for a simple way of doing it so i can comprehend how it works

thanks

+4  A: 

You cannot use JavaScript to control the flow of PHP code in the way you've provided. The reason the record is always deleted is because the PHP interpreter kicks in as soon as it sees the <?php identifier, so the statement will always be executed.

I would try something like this:

  • Use a standard form and the post method to submit the id of the record to be deleted
  • Use JavaScript to enhance the form; bind to the submit event and then you can ask for confirmation, only allowing the form to submit if they say okay.

In this way, the JavaScript enhances functionality and it will degrade gracefully. You'll still have to implement all the business logic of deleting the row from the PHP script that handles the form submission.

Peter
+2  A: 

From what I can gather you are failing to understand that PHP runs on the server while Javascript runs on the client. Follow @Peter's advice, also read and learn more before diving head first into it and coming up with weirdness like that. A rudimentary fix would be something like:

<script type="text/javascript">
function deleteRecord(id) {
    if(window.confirm("Are you sure you want to delete that record?")) { 
        window.location.href = 'myScript.php?id=' + id;
    }
}
</script>

In your myScript.php:

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

you can use something like this:

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

and then in your html:

<a href="delete.php?id=42" onclick="return askUser();">delete record</a>

of course you need to create a file delete.php which handles all your logic for deleting.

ps. in real life you should avoid inline javascript, i'm just using it here for this short example

knittl