Hi,
I have implemented a JavaScript function that should allow the user to confirm if they want to delete a record or not. This is the code I have:
if(isset($_POST['delete'])) { ?>
<script type="text/javascript">
<!--
function confirmation() {
var answer = confirm("Are you sure you want to delete?")
if (answer){
<?php
mysql_query("DELETE FROM tblgbs WHERE gbID = $gbID") or die(mysql_error());
mysql_query("DELETE FROM tblgb WHERE gbID = $gbID") or die(mysql_error());
$success_msg = '<div class="errormsg">Deleted</div>';
?>
}
else{
<?php
$success_msg = '<div class="errormsg">Not Deleted</div>';
?>
}
}
//-->
</script>
The problem is that the first time I enter the delete page, I do not get the confirm box, it just deletes the record. The second problem I have is that even if I select Cancel, it still deletes the record.
I am using the following submit button to trigger the function:
<input class="subbtn" type="submit" name="delete" value="Delete" onclick="confirmation()" />
Please can someone have a look at this and tell me where I am going wrong.
Many thanks,
John
PHP is a server-side language, which means all of the code is processed on the server. This is done before any output (HTML and Javascript) is sent to the user's browser. Therefore, in your script, the PHP portion is processed first, deleting the record, and then the Javascript and HTML is passed on to the user.
Your script is expecting that the code is processed in the following order:
Some Javascript
Some PHP
Some more Javascript
Some HTML
This is not correct.
You will need to alter your document to send the required HTML and Javascript, receive the user's answer, and then call another script with the request to delete the record.