views:

531

answers:

2

table department(department_id, name) table category(category_id, department_id, name)

I want to implement the idea that when i change department in drop down list, all categories will change according to the department value

It 's my jquery script

{literal}
<script type="text/javascript">
$(document).ready(function(){
  $('#department').change( function() {
    var departmentVal = $(this).val();
    $("#category option").remove();
    $.getJSON("ajax.php",{departmentId: $(this).val(), dataType: "json", ajax: 'true'},
      function(j){
        var options = '';
          for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].category_id + '">' + j[i].name + '</option>';
           }
         $("#category").html(options);  
    })
  });
});
</script>
{/literal}

I want to know how can i implenent code for class Ajax in file ajax.php to return json

I do it like it before but nothing happen b/c i dont use class

$category= array();
while($grab = $db->fetch_array($result)) {
  $category[] = array('optionValue' => $grab['category_id'], 'optionDisplay' => $grab['name']);
}
echo json_encode($category);

Now i want to use class with PDO to implement this idea, help me plz

+1  A: 

I can help with the concept and algorithm:

  1. Display the department dropdown and add a jquery to handle change event.
  2. Load only JSON data for categories is good, but sometimes it will not work in IE and safari. One of robust way to do it is load a complete select with AJAX, then replace the existing category dropdown.
jQuery(function($){
  $('#department').change( function() {
    var departmentVal = $(this).val();
    var cat_parent =  $("#category").parent();
    cat_parent.html("Loading...");
    $.get("category_select.php",
          {departmentId: departmentVal},
          function(data){
            cat_parent.html(data);
          })
  });
});

category_select.php will need to return data with format:

<select id="category">
  <option>...</option>
</select>

Make sure you put the category select inside a parent that have no other children:

<span>
  <select id="category">
    <option>Select a department first</option>
  </select>
</span>

This method will working in latest IE, Safari, Google Chrome, and Firefox.

Donny Kurnia
A: 

You should be able to implement this with jQuery Smarty with it's auto_update modifier. http://www.balupton.com/sandbox/jquery-smarty/demo/

balupton