javascript confirm function to control php/mysql row deletion

User clicks delete then i want to ask them if they are sure the want to delete the charge/row in database using javascript confirm function.

When I hit cancel it is still calling the php and deleting the data row.

How do i get this to work with javascript. Code below.
<?
 
if ($cmd == "delete_charge") { ?>
	
<script type="text/javascript">
var answer = confirm ("Are you sure you want to delete this charge?")
if (answer) {
<?
 
$sql = "
DELETE
from
charges
where charge_id = '" . $charge_id . "'
";
 
$rst = $con->execute($sql);
 
 
?>
} else {
window.location = "file.php?contact_id=<?=$contact_id?>"
}
</script> 
	
<script type="text/javascript">
<!--
window.location = "file.php?contact_id=<?=$contact_id?>"
//-->
</script>
 
 
<?
	
}
 
?>

Open in new window

LVL 1
pdheadyAsked:
Who is Participating?
 
alien109Commented:
javascript executes client side, php executes serverside. in other words, you can't do what you are trying to do there. when the page is being processed by the server, it is executing the php delete code, before it even gets sent.
0
 
aldanchCommented:
Line #6. Missing a semi-colon at the end?
var answer = confirm ("Are you sure you want to delete this charge?")

Open in new window

0
 
pdheadyAuthor Commented:
no the popup works, for some reason whether i select ok or cancel both will call the php script.
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Scripting_GuyCommented:
echoing javascript code does not halt your php code, no matter what the js code is.

if $cmd is "delete_charge", your php-script first echo some stuff (it doesnt care what it echos, it could be javascript or just some foobars) and then executes the delete statement. your row is deleted before you can even click on your browser's popup.

JS and PHP do NOT interact with each other directly.

the code in your browser looks like this:

<script type="text/javascript">
var answer = confirm ("Are you sure you want to delete this charge?")
if (answer) {
} else {
window.location = "file.php?contact_id=1234"
}
</script>
<script type="text/javascript">
<!--
window.location = "file.php?contact_id=1234"
//-->
</script>

Which means: if you click yes, nothing happens at first. if you click now, window.location changes. then the code goes on and your window.location changes anyway.
0
 
pdheadyAuthor Commented:
ok thanks, i need to call the javascript function before i hit the script again.
0
 
pdheadyAuthor Commented:
Thanks again.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.