Reputation: 188
<select name="class">
<option> --select class-- </option>
</select>
<select name="subject">
<option> --select subject-- </option>
</select>
now i want to use the ajax to populate the subject list box.. I have no idea how to do it.
Upvotes: 1
Views: 621
Reputation: 1038710
You could subscribe to the change event of the first select box and then trigger an ajax request to your server by passing the selected value. Then in the success callback of this request you could use the JSON array returned by the server to update the contents of the second select box. Here's an example of how to achieve this using jQuery:
$(function() {
$('.class').change(function() {
// when the value of the first select changes trigger an ajax request
var value = $(this).val();
$.getJSON('/script.cgi', { selectedValue: value }, function(result) {
// assuming the server returned json update the contents of the
// second selectbox
var subject = $('.subject');
subject.empty();
$.each(result, function(index, item) {
result.append(
$('<option/>', {
value: item.value
text: item.text
})
);
});
});
});
});
and the JSON returned from the server could look like this:
[ { value: '1', text: 'subject 1' }, { value: '2', text: 'subject 2' } ]
Upvotes: 1