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.

Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.