Creating ajaxy Chained Selects with jQuery

Tutorials

Today we will talk about creating dependent (chained) selects for your projects. This can be any related elements at your website. As example dependent fields to select your profession, mobile phone, or location (which can include Country, State, Region etc). One important note – we will need all this working using AJAX technology (to make functionality fast and smooth). And, jQuery library provide us with that plugin – jquery.chainedSelects.js. I will show you how to create chained fields using this plugin.

Plugin itself you always can download here. Ok, here are online demo and downloadable package:

Live Demo
download in package

Ok, download the example files and lets start coding !


Step 1. SQL

We will keep our data in database (tables with countries, states and regions). I don`t will show you FULL sql here (its pretty big), but I will show you structures and few records per table. Full SQL will available in package (check for sql.sql file inside package). As you can see – I selected prefix ‘s85′ for tables – this is number of our current tutorial. You always can use your own table names if you wish.


01 -- countries
02 CREATE TABLE `s85_countries` (
03   `country_code` varchar(2) NOT NULL,
04   `country_name` varchar(255) NOT NULL,
05   PRIMARY KEY  (`country_code`)
06 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
07
08 INSERT INTO `s85_countries` (`country_code`, `country_name`) VALUES
09 ('AR''Argentina'),
10 ('AU''Australia'),
11 ('BR''Brazil');
12
13 -- states
14 CREATE TABLE `s85_states` (
15   `id` int(11) NOT NULL AUTO_INCREMENT,
16   `country_code` varchar(3) NOT NULL,
17   `state_name` varchar(255) NOT NULL,
18   PRIMARY KEY (`id`)
19 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
20
21 INSERT INTO `s85_states` (`id`, `country_code`, `state_name`) VALUES
22 (1, 'US''alabama'),
23 (2, 'US''alaska'),
24 (3, 'US''arizona');
25
26 -- regions
27 CREATE TABLE `s85_regions` (
28   `id` int(11) NOT NULL AUTO_INCREMENT,
29   `state_id` int(11) NOT NULL,
30   `region_name` varchar(255) NOT NULL,
31   PRIMARY KEY (`id`)
32 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
33
34 INSERT INTO `s85_regions` (`id`, `state_id`, `region_name`) VALUES
35 (1, 1, 'auburn'),
36 (2, 1, 'birmingham'),
37 (3, 1, 'columbus, GA');

Step 2. PHP

index.php

This is our main PHP file, I using this file to generate our FORM with necessary selects for country, state and region fields. And, this file also contain code for ajax calls of states (of selected country) and regions (of selected state).

01 <?
02 require_once('classes/CMySQL.php');
03
04 if (version_compare(phpversion(), "5.3.0"">=")  == 1)
05   error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
06 else
07   error_reporting(E_ALL & ~E_NOTICE);
08
09 // return states of country
10 if ($_GET['action'] == 'get_states') {
11     $sCountryName $GLOBALS['MySQL']->escape($_GET['_value']);
12
13     $aRet[] = array(0 => 'any');
14     $aStates $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_states` WHERE `country_code`='{$sCountryName}'"'id''state_name');
15     foreach ($aStates as $iStateId => $sStateName) {
16         $aRet[] = array($iStateId => $sStateName);
17     }
18
19     echo json_encode($aRet);
20     exit;
21 }
22 if ($_GET['action'] == 'get_regions') {
23     $iStateID = (int)$_GET['_value'];
24
25     $aRet[] = array(0 => 'any');
26     $aRegions $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_regions` WHERE `state_id`='{$iStateID}'"'id''region_name');
27     foreach ($aRegions as $iRegionId => $sRegionName) {
28         $aRet[] = array($iRegionId => $sRegionName);
29     }
30
31     echo json_encode($aRet);
32     exit;
33 }
34
35 $sCountryOptions '';
36 $aCountries $GLOBALS['MySQL']->getPairs("SELECT * FROM `s85_countries`"'country_code''country_name');
37 foreach ($aCountries as $sCode => $sName) {
38     $sCountryOptions .= '<option value="'.$sCode.'">'.$sName.'</option>';
39 }
40 $sCountries '<select name="country" id="country">'.$sCountryOptions.'</select>';
41
42 echo <<<EOF
43 <link href="css/style.css" rel="stylesheet" type="text/css" />
44 <script src="js/jquery.js" type="text/javascript"></script>
45 <script src="js/jquery.chainedSelects.js" type="text/javascript"></script>
46 <script src="js/main.js" type="text/javascript"></script>
47
48 <div class="example">
49     <form action="" method="post">
50         <div><label for="country">Country</label>{$sCountries}</div>
51         <div><label for="state">State</label>
52             <select name="state" id="state""><option value="0">any</option></select>
53         </div>
54         <div><label for="region">Region</label>
55             <select name="region" id="region""><option value="0">any</option></select>
56         </div>
57         <div><input name="submit" type="submit" value="Send this info" /></div>
58     </form>
59 </div>
60 EOF;
61
62 if ($_POST) {
63     // draw debug information
64     echo '<pre>';
65     print_r($_POST);
66     echo '</pre>';
67 }
68
69 ?>

Make attention, I using my own class for work with database – ‘classes/CMySQL.php’. This file already available in package. Commonly – you can use same, or similar class for your own projects. This just give some comfort with working with database. One thing what you will need to do – configure database connection params inside that file (in top of its code).

Step 3. JS

js/jquery.js and js/jquery.chainedSelects.js

This is just ordinary jQuery library with our new plugin – chainedSelects. Both files available in package.

js/main.js

01 $(function() {
02   $('select[name=country]').chainSelect('#state','index.php?action=get_states', {
03     before:function (target) {
04       $(target).css('visibility','hidden');
05     },
06     after:function (target) {
07       $(target).css('visibility','visible');
08     }
09   });
10   $('#state').chainSelect('#region','index.php?action=get_regions', {
11     before:function (target) {
12       $(target).css('visibility','hidden');
13     },
14     after:function (target) {
15       $(target).css('visibility','visible');
16     }
17   });
18 });

Syntax of chainedSelects using easy, we can point which URL will called when we changing selects, also we can perform some extra actions before request, and after.

Step 4. CSS

css/style.css

01 body {
02     background:#eee;
03     margin:0;
04     padding:0;
05 }
06 .example {
07     background:#FFF;
08     width:400px;
09     border:1px #000 solid;
10     margin:20px auto;
11     padding:15px;
12     -moz-border-radius:3px;
13     -webkit-border-radius:3px;
14 }
15 .example form {
16     background:#EEE;
17     border:1px #DDD solid;
18     padding:10px;
19     -moz-border-radius:3px;
20     -webkit-border-radius:3px;
21 }
22 .example form div {
23     margin:10px;
24 }
25 .example form div label {
26     display:block;
27     width:100px;
28     float:left;
29 }
30 .example form div select {
31     width:200px;
32 }

Live Demo
download in package

Conclusion

In result, now we have pretty nice dependent selectors where we can choose our location. Happy coding. Good luck in your projects!

Rate article