Sample Use of JavaScript Confirm Pop Up Boxes

I’m gonna give you an example on how to use JavaScript confirm pop up boxes to delete a database record.

JavaScript Confirm Pop Up Box

File Name: index.php

<html>
   <head>
        <title>Sample Use of JavaScript Confirm Pop Up Boxes</title>
        <script type='text/javascript'>
            function delete_user( id ){
                var answer = confirm('Are you sure you want to delete this record?');
                if ( answer ){ //if user clicked ok
                    window.location = 'index.php?action=delete&id=' + id;
                } //you can add else here
            }
        </script>
   </head>
<body>
   <p>
   <?php
    if($_REQUEST['action']=='delete'){
    include 'config_open_db.php'; //for database connection
        $sql = "DELETE FROM users WHERE id = {$_REQUEST['id']}";
        mysql_query ( $sql ) or die('Database Error: ' . mysql_error());
        echo "User Deleted!";
      }
   ?>
   </p>

   <a href='#' onclick="delete_user( 3 );">Delete</a>

</body>
</html>

Here’s how it works:
1. When you run this code, you will see a delete link.
2. After clicking that link, a JavaScript Pop Up Box will appear saying “”Are you sure you want to delete this record?”.
3. If you click on “Cancel”, nothing will happen aside from the box will disappear.
4. If you click on “OK”, the page will be redirected to itself together with the parameters “action” and “id”, it is on this part window.location = ‘index.php?action=delete&id=’ + id;
5. It will then evaluate our PHP script to delete the record from the database.

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top