After an AJAX Post request, I'm trying to retrieve from my view some list values contained in a variable. The idea is to use these values to populate a dropdown. But my variable seems empty. I thought that it was because I initially used a 'return render()', but even with a 'return HttpResponse()' it doesn't work.
This is my views.py:
def MyView3(request):
if request.method == 'POST' and request.is_ajax:
myVariable = ["1", "2", "3", "4", "5"]
print(myVariable)
return HttpResponse(myVariable)
else:
return render(request,'home3.html')
This is 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">
{% for item in myVariable %}
<option val="{{ item }}"> {{ item }} </option>
{% endfor %}
</select>
<script type="text/javascript">
function dropdownChange () {
var selectedValue = $(".toChange option:selected").val();
$.ajax({
type: 'POST',
data: {'myVal': selectedValue},
});
var mylist = '{{myVariable}}';
alert(mylist);
}
$(".toChange").change(dropdownChange);
</script>
</form>
The idea here is to triger the AJAX call when I select a new value in my 'myVal' dropdown. The call works since the view is correctly activated, as 'print(myVariable)' shows the expected result in the console. Moreover, my alert pop-up is displayed. Yet, it is empty. I would need it to show the values contained in 'myVariable', so '["1", "2", "3", "4", "5"]'. I assume it should be something simple, but I couldn't figure out what. Could you please help?