I am facing an issue with implementing a dropdown that triggers an AJAX call when a new value is selected. In my setup, the AJAX script calls a Django view which returns a list of values. The problem arises when I try to populate a second dropdown with these values, as I can't seem to figure out the correct way to do it.
Below is the snippet of my HTML code:
<form class="wrapper" action="" method="post"> {% csrf_token %}
<select name="myVal" class="toChange">
<option val="1">1</option>
<option val="2">2</option>
</select>
<select id="dep" name="dep"> </select>
<script type="text/javascript">
function dropdownChange () {
var selectedValue = $(".toChange option:selected").val();
$.ajax({
url: '/myApp/templates/3/',
type: 'POST',
data: {'myVal': selectedValue},
success: function(result) {
alert(result);
}
});
}
$(".toChange").change(dropdownChange);
</script>
</form>
And this is the relevant snippet from my views.py file:
@csrf_exempt
def MyView3(request):
if request.method == 'POST' and request.is_ajax:
myVariable = json.dumps(["1", "2", "3", "4", "a"])
return HttpResponse(myVariable , content_type='application/json')
else:
return render(request,'home3.html')
Although the AJAX call successfully returns the list of values "1,2,3,4,a", I am unsure of how to use these values to populate the "dep" dropdown. I have attempted to include the following code in the script, but it did not yield any results:
var select = document.getElementById("dep");
var options = result
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
I am uncertain whether this code is misplaced or if there is a more appropriate approach. Any guidance on how to achieve this would be greatly appreciated. Thank you.