Dynamic dropdown with php/mysql/ajax problem

edited June 2012 in News & Announcements
Hello,

I don't know if this question belongs here, since I think it is a jquery issue, but hopefully someone can help.

I am trying to create dynamic dropdown lists with PHP MySQL and AJAX.

I have a category select and a sub category select.

When a user selects a category, the sub cateory dropdown should be populated from the database with all the sub categories that belong to the selected category.

In my controller I have this code:

$options = $this->sub_categories_model->find_all(array('cat_id'=>$catId), 'title asc'); $arr = array(); foreach($options as $opt): $arr[] = array('id'=>$opt->id, 'title'=>$opt->title); endforeach;

In my view my html select:
<select name="category" id="category"> <option value="6" label="Community">Community</option> <option value="1" label="For Sale">For Sale</option> <option value="2" label="Need a Lift">Need a Lift</option> <option value="3" label="Property">Property</option> <option value="5" label="Services">Services</option> <option value="4" label="Vehicles">Vehicles</option> </select> <select id="subcatetory"></select>

My jquery code:
$('#category').change(function() { var catId = $(this).val(); var select = $('#subcategory'); if(select.prop) var options = select.prop('options'); else var options = select.attr('options'); $('option', select).remove(); $.ajax({ type: "POST", url: "<?php echo site_url(); ?>postanad/getSubCategories", data: {catId: catId}, success: function(data) { console.log(data); $.each(data, function(i, val) { //options[options.length] = new Option(val, i); console.log(val); }); } }); });

If I code in my controller:
print_r($arr);

In my view I see this:
Array ( [0] => Array ( [id] => 3 [title] => Clothes & Accessories ) [1] => Array ( [id] => 1 [title] => Electronics ) [2] => Array ( [id] => 4 [title] => Home & Garden ) [3] => Array ( [id] => 5 [title] => Miscellaneous ) [4] => Array ( [id] => 2 [title] => Sports & Leisure ) )

If I code in my controller:
echo json_encode($arr);

In my view I see this:
[{"id":"3","title":"Clothes & Accessories"},{"id":"1","title":"Electronics"},{"id":"4","title":"Home & Garden"},{"id":"5","title":"Miscellaneous"},{"id":"2","title":"Sports & Leisure"}] [ { " i d " : " 3 " , " .... ]

So of course, something is wrong, since the $.each(data, function(i, val) is breaking the array letter by letter which is not good.

Can someone please help?

Comments

Sign In or Register to comment.