Skip to main content Jump to list of all articles

PHP and jQuery checkbox array with a hint of Jquery UI

I have been learning jQuery alongside PHP to help with my event manager project. Here is a tutorial on how to get the values of a checkbox array, post it via a jQuery Ajax call and subsequently delete the values from an MYSQL database. This tutorial also makes use of the jQuery UI which we will use to display our dialogues.  This script has now been included in wow playground with new and updated features.

Prerequisites

I am assuming that you have access to a PHP web server and have a MYSQL database. I highly recommend Xampp for your testing needs. I am also assuming that you know the basics on uploading and using an FTP program and have the use of a text editor or IDE.

Database Setup

For an in depth explanation on how to setup the database setup visit one of my previous tutorials. Download the source files and edit config.php in the lib directory to include the details of your database. Upload them to your server. Navigate using your browser to the files. For example: https://localhost/jquery_checkboxes/lib/setup.php
Click on the Setup button and this will setup the database for you and re-direct you to index.php.

Index.php

The main files are index.php, checkbox.js and process.php. First we will have a look at the main part of index.php

<body>
   <h1>PHP Checkbox Array Tutorial</h1>
      <div id="dialog-confirm" title="Delete Item(s)?">
         <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;">nbsp;</span>
                These items will be permanently deleted and cannot be recovered. Are you sure?
         </p>
      </div>
<?php
      require('lib/Database.class.php');
      $db->connect();
      $query='SELECT * FROM events';
      $rows=$db->query($query);

      if (mysql_num_rows($rows)) {?>
           <form name='delete_form' id='delete_form' action='' method='post'>
           <input type="checkbox" id="selectAll" name="deleteCB[]"  /><br/>
                <?php while ($result = $db->fetch_array($rows))
                     {
                        $id = $result['id'];
                        $event = $result['event'];
                        echo "<input type='checkbox' name='deleteCB[]'  value='$id' />$event<br/>";
                     }
                        echo "<input type='submit' id='deleteBtn' value='Delete' name='deleteBtn' />";
                        echo "</form>"; }  //end if?>
</body>
</html>

Here we fetch the data from the MYSQL database and place it into a form. Line 21 is very important as it contains our checkbox array name deleteCB[] which we use via jQuery to obtain our values.

Checkboxes.js

$(function() {
    $("#selectAll").click(function()
      {
        var checked_status = this.checked;
        $('input[name="deleteCB[]"]').each(function()
            {
              this.checked = checked_status;
            });
       });
    $("#delete_form").submit(function(e) {
          return false;       });

var $dialog = $('<div></div>')
    .html('Item(s) have been successfully deleted')
    .dialog({
          autoOpen: false
});
var $dialog2 = $('<div></div>')
   .html('No checkboxes are checked!')
   .dialog({
	  autoOpen: false,
	  title: 'Error'
});
$("#deleteBtn").click(function() {
     if ($('input[type=checkbox]').is(':checked')){
        $( "#dialog-confirm" ).dialog({
                modal: false,
                buttons: {
                     "Delete all items": function() {
                          $(this ).dialog( "close" );
                          var data = $(":checkbox:checked").map(function(i,n)
                                   {
                                      return $(n).val();
                                   }).get();
                                    $.post("process.php", { 'deleteCB[]': data },
                                          function(){
                                                 $('body').load('index.php', function() {
                                                 $dialog.dialog({title: 'Item(s) Deleted'});
                                                  });
                                   });
                          },
                Cancel: function() {
                 $( this ).dialog( "close" );
                 return false;
             }
      } //end buttons
    });
    }
    else
    {
         $dialog2.dialog("open");
    }
   });
});

Now lets get to grips with checkbox.js. Lines 2-11 are for selecting or de-selecting all checkboxes. Lines 13-23 are for the creation of the jquery UI Dialogues in which we use for displaying messages. Line 24 is the start of the click event when the delete button is pressed a event is triggered. Line 25 checks to see if any checkboxes have been selected. If there are no checkboxes selected it fires a jQuery UI error dialog. If there is a checkbox selected a jQuery UI confirmation dialog appears to check whether you want to delete the items selected. Clicking on Delete all items will take you to line 31 where we assign the variable data to get the values of the checked checkboxes. Line 35 is the start of our jQuery Ajax call which posts the deleteCB[] with its corresponding value to the file process.php. Then we reload the page once the call has been processed and display a dialog to confirm that the deletion has been successful.

Process.php

<?php
require ('lib/Database.class.php');
$db->connect();
    foreach ($_POST['deleteCB'] as $value)
    {
      $query_delete = "DELETE FROM events WHERE id='$value'";
      $db->query($query_delete);
    }
$db->close();
?>

Process.php is a simple foreach loop which receives the data from checkboxes.js and deletes the values from the database.

Download


Discover more from WorldOWeb

Subscribe to get the latest posts sent to your email.

7 replies on “PHP and jQuery checkbox array with a hint of Jquery UI”

there is an error of the script

Message:Could not connect to server: DB_SERVER.MySQL Error:php_network_getaddresses: getaddrinfo failed: No such host is known.

Nashirmohammad
Nashirmohammad On

Very Good article. Thanks

please put this code on the top of setup.php page. otherwise Warning: Cannot modify header information – headers already sent by (output started at Cn line 57)

Sample Templates
Sample Templates On

Great article. Concise and to the point.actually very interesting pack of articles! have bookmarked and shared with face book!!

Comments are closed.