I have a bunch of code that I think is supposed to populate a "category" select box from the value in another "subject" select box.
views.py
def get_categories(request, subject_id):
subject = Subject.objects.get(pk=subject_id)
categories = subject.category_set.all()
category_dict = {}
for cat in categories:
category_dict[cat.id] = cat.name
return HttpResponse(json.dumps(category_dict), content_type="application/json")
urls.py
url(r'^get_categories/(?P<subject_id>\d+)/$', views.get_categories, name='get_categories'),
jquery
$(document).ready(function(){
$('select[name=subject]').change(function(){
subject_id = $(this).val();
request_url = '/get_categories/' + subject_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data[0], function(key, value){
$('select[name=category]').append('<option value="' + this.key + '">' + this.value +'</option>');
});
}
})
})
});
the request is passing the json data as far as I can tell, Javascript is giving an error:
Uncaught TypeError: Cannot read property 'length' of undefined
I tired changing data[0] to data and that removed the error but all the fields showed up as undefined in the select box.