Javascript confirm with PHP function afterward

Catia picture Catia · Dec 30, 2011 · Viewed 22.6k times · Source

I would like a way to have a confirm box pop up when a user clicks "delete" to remove a record.

Something like:

<script language="JavaScript"  type="text/javascript" >

function confirmDelete() {
    if(confirm("Would you like to delete the selected products?")) {
        <?php 
            $allCheckBoxId = $_POST['checkbox'];
            array_map ('mysql_real_escape_string', $allCheckBoxId);
            $ids = implode(",", $allCheckBoxId);
            $sql = "DELETE FROM products WHERE `id` IN ($ids)";
            mysql_query($sql);
        ?>
    }
}

</script>

With an onclick:

echo "<input type='submit' name='submit' value='Delete'  onclick='confirmDelete()' />";

But I know it's not possible to be using Javascript & PHP together like this. Is there another way to do this? Maybe PHP has its own kind of confirm? Please give any ideas!

Thank you.

Answer

Jules picture Jules · Dec 30, 2011

It is pretty easy to make use of AJAX for this case. Simply place your PHP in the scriptDelete.php file and make sure you pass the proper arguments and their values in the data property. For this example I just pass an id of 5.

<script type="text/javascript">

    function confirmDelete() {
        if (confirm('Are you sure you want to delete this?')) {
            //Make ajax call
            $.ajax({
                url: "scriptDelete.php",
                type: "POST",
                data: {id : 5},
                dataType: "html", 
                success: function() {
                    alert("It was succesfully deleted!");
                }
            });

        }
    }
</script>

<input type='submit' name='submit' value='Delete'  onclick='return confirmDelete()' />

Another way would be to post the form back to its own page like:

<form method="post" action="yourpage.php">
    <input type="submit" name="submit" value="delete" onclick="return confirm('Are you sure you want to delete this?')" />
</form>

So you simply post the form back to yourpage.php and on top of this page you do something like:

<?php

   //Means the form was submitted
   if ($_POST['submit']) {
      $id = $_POST['idToDelete'];
      $query = "DELETE FROM products WHERE id = " . mysql_real_escape_string($id);
      mysql_query($query) or die(mysql_error());
   }
?>