PHP Dynamic Select options Via Ajax is tutorial for those who want to make 2 dynamic select options in form. one is dependent on other and data fetched from MySQL Database.
Website for Complete Tutorial is Crewow
- Open your Dreamweaver or Notepad editor and create new PHP Page and name it myform.php
- Now Create only one Table for Categories like this
CREATE TABLE IF NOT EXISTS `category` ( `SrNo` int(11) NOT NULL AUTO_INCREMENT, `Category` varchar(50) NOT NULL, `SubCategory` varchar(100) NOT NULL, PRIMARY KEY (`SrNo`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
- Now insert some sample values like this
INSERT INTO `category` (`SrNo`, `Category`, `SubCategory`) VALUES (1, 'Electronics', 'Mobile'), (2, 'Electronics', 'Tablet'), (3, 'Electronics', 'IPad'), (4, 'Electronics', 'ITab'), (5, 'Electronics', 'Television'), (6, 'Electronics', 'Camera'), (7, 'Electronics', 'Laptop'), (8, 'Electronics', 'LCD'), (9, 'Electronics', 'Computer'), (10, 'Books', 'Magazines'), (11, 'Books', 'Journals'), (12, 'Books', 'Course Books');
- In myform.php for making Category Field use below PHP Lines to get data from Category Table. please write these lines inside <form></form> tags.
<?php echo "<select name='Category' id='Category'>"; echo "<option value='' disabled='' selected='' >--Select Category--</option>"; $q6=mysql_query("select DISTINCT Category from category"); while($r6=mysql_fetch_array($q6)) { echo "<option value='$r6[0]' >$r6[0]</option>"; } echo "</select>"; ?>
- Now make Sub Category select options like below. DO NOT Worry about Sub category options, we will load sub category via Ajax later.
<?php echo "<select name='SubCategory' id='SubCategory'>"; echo "<option value='' disabled='' selected='' >--Select Sub Category--</option>"; echo "</select>"; ?>
- Now we need to make another PHP Page in which we will run query for sub category fields. Name it Ajax_SubCategory.php
<?php Config.php file for connecting to PHP. include('config.php'); id will be posted via Ajax script. please see point no.7 if($_POST['id']) { $id=$_POST['id']; $sql=mysql_query("select SubCategory from category where Category='$id'"); while($row=mysql_fetch_array($sql)) { $data=$row['SubCategory']; echo '<option value="'.$data.'">'.$data.'</option>'; } } ?>
- Now we will call Ajax_SubCategory.php via Ajax and Jquery in myform.php. please includeJquery in your myform.php
<script type="text/javascript"> $(document).ready(function(){ Below line will get value of Category and store in id $("#Category").change(function() { var id=$(this).val(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "Ajax_SubCategory.php", data: dataString, cache: false, success: function(html) { This will get values from Ajax_SubCategory.php and show in Subcategory Select option $("#SubCategory").html(html); } }); }); }); </script>
No comments:
Post a Comment