article

Sunday, June 3, 2012

Dynamic Loading of ComboBox using jQuery and Ajax in PHP

Dynamic Loading of ComboBox using jQuery and Ajax in PHP

Download
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.livequery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('.parent').livequery('change', function() {
  $(this).nextAll('.parent').remove();
  $(this).nextAll('label').remove();
  $('#show_sub_categories').append('<img src="loader.gif" style="float:left; margin-top:7px;" id="loader" alt="" />');
  $.post("get_chid_categories.php", {
   parent_id: $(this).val(),
  }, function(response){
   
   setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
  });
  return false;
 });
});
function finishAjax(id, response){
  $('#loader').remove();
  $('#'+id).append(unescape(response));
} 
</script>
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
.parent{ padding:3px; width:150px; float:left; margin-right:12px;}
.both{ float:left; margin:0 0px 0 0; padding:0px;}
</style>
</head>
<?php include('dbcon.php');?>
<div style="padding-left:30px; height:710px;">
 <h1>Dynamic Loading of ComboBox using jQuery and Ajax in PHP</h1>
 <br clear="all" /><br clear="all" />
 <div id="show_sub_categories">
  <select name="search_category" class="parent">
  <option value="" selected="selected">-- Categories --</option>
  <?php
  $query = "select * from ajax_categories where pid = 1";
  $results = mysql_query($query);
  while ($rows = mysql_fetch_assoc(@$results))
  {?>
   <option value="<?php echo $rows['id'];?>"><?php echo $rows['category'];?></option>
  <?php
  }?>
  </select> 
 </div>
 <br clear="all" /><br clear="all" />
</div>
//dbcon.php
<?php
$link = mysql_connect('localhost', 'root', 'ednalan');
@mysql_select_db('dbname',$link); 
?>
//get_chid_categories.php
<?php
include('dbcon.php');
if($_REQUEST)
{
 $id  = $_REQUEST['parent_id'];
 $query  = "select * from ajax_categories where pid = ".$id;
 $results  = @mysql_query( $query);
 $num_rows = @mysql_num_rows($results);
 if($num_rows > 0)
 {?>
  <select name="sub_category" class="parent">
  <option value="" selected="selected">-- Sub Category --</option>
  <?php
  while ($rows = mysql_fetch_assoc(@$results))
  {?>
   <option value="<?php echo $rows['id'];?>"><?php echo $rows['category'];?></option>
  <?php
  }?>
  </select> 
 <?php 
 }
 else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
?>

Related Post