8

I am trying to create a dynamic set of dropdown boxes, using jQuery/AJAX and PHP/MySQL. The first dropdown box will be populated when the page loads based on values from a database. The second dropdown box should display a set of values based on the selection from the first dropdown box. I know there have been similar questions asked on here before, but I haven't found a solution that matches my scenario.

My query to generate a JSON encoded list of values for the second drop down is functioning, but I am having issues populating it into the actual dropdown form element. Any ideas on where I'm going wrong.

Javascript:

<script>
$().ready(function() {

    $("#item_1").change(function () {   

      var group_id = $(this).val();

       $.ajax({
            type: "POST", 
            url: "../../db/groups.php?item_1_id=" + group_id, 
            dataType: "json",
            success: function(data){
                //Clear options corresponding to earlier option of first dropdown
                $('select#item_2').empty(); 
                $('select#item_2').append('<option value="0">Select Option</option>');
                //Populate options of the second dropdown
                $.each( data.subjects, function(){    
                    $('select#item_2').append('<option value="'+$(this).attr('group_id')+'">'+$(this).attr('name')+'</option>');
                });
                $('select#item_2').focus();
            },
            beforeSend: function(){
                $('select#item_2').empty();
                $('select#item_2').append('<option value="0">Loading...</option>');
            },
            error: function(){
                $('select#item_2').attr('disabled', true);
                $('select#item_2').empty();
                $('select#item_2').append('<option value="0">No Options</option>');
            }
        })  

    }); 
});

</script>

HTML:

<label id="item_1_label" for="item_1" class="label">#1:</label>
<select id="item_1" name="item_1" />
    <option value="">Select</option>
    <?php
        $sth = $dbh->query ("SELECT id, name, level 
                             FROM groups
                             WHERE level = '1'
                             GROUP by name
                             ORDER BY name");                                   
        while ($row = $sth->fetch ()) { 
            echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'."\n";       
        }
     ?>
</select>

<label id="item_2_label" for="item_2" class="label">#2:</label>
<select id="item_2" name="item_2" />                        
</select>

PHP:

<?php

require_once('../includes/connect.php');        

$item_1_id = $_GET['item_1_id'];

$dbh = get_org_dbh($org_id);

$return_arr = array();

$sth = $dbh->query ("SELECT id, name, level 
                     FROM groups
                     WHERE level = '2'
                     AND parent = $item_1_id
                     GROUP by name
                     ORDER BY name");   

while ($row = $sth->fetch ()) { 

    $row_array = array("name" => $row['name'], 
                       "id" => $row['id']); 

    array_push($return_arr,$row_array);     
}

echo json_encode($return_arr);

?>  

Sample JSON Output:

[{"name":"A","id":"0"},{"name":"B","id":"1"},{"name":"C","id":"2"}]
7
  • Are you getting any JS-errors? Commented Jan 5, 2012 at 20:41
  • Could you provide an example of your JSON as well? Commented Jan 5, 2012 at 20:43
  • Firebug is displaying "object is undefined, length = object.length" for the jQuery script, after the first dropdown box is changed. No errors on page load. Commented Jan 5, 2012 at 20:45
  • Just edited question to include sample JSON output. Commented Jan 5, 2012 at 20:47
  • Do you know which row the error occurs on? I've added an answer with a few things you can look at. Commented Jan 5, 2012 at 20:51

1 Answer 1

4

First, your document-ready looks a bit off, it should either be $(document).ready(function(){}); or it could be just $(function(){});.

Second, you looping over the JSON result looks a bit odd as well. Try something like this instead:

$.each(data.subjects, function(i, val){    
   $('select#item_2').append('<option value="' + val.id + '">' + val.name + '</option>');
});
Sign up to request clarification or add additional context in comments.

4 Comments

Made the changes you suggested, but still no go. Using jQuery 1.7, it says the error is on line 632.
@Michael Okay, since I don't have all your code, I don't know which row that is. Can you look it up for me, or highlight it in your code sample?
@Michael Well, the problem is most likely not in the jQuery file, but when I look at that row in the jQuery source, that is where they declare the each method. That makes me think that it is you loop that is the problem. How come you pass data.subjects into the loop. Does the JSON-result contain more than what you showed me in the example code?
@Michael If the JSON-result is just what you've showed, then try passing just data to the each function, instead of data.subjects. If that doesn't help, please do a console.log(data); in the success callback, and post what is being logged, so that I know what data contains.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.