Django: How to retrieve in an AJAX POST request the value of two different variables?

Viewed 41

I'm trying to send to my Django view two values from two different dropdowns but it doesn't work. Only the first dropdown value is sent to the view.

Let's say I have the following view:

def MyView(request):

    if request.method == 'POST' and request.is_ajax:

        result_1 = request.POST.get('d1')
        print(result_1)
        result_2 = request.POST.get('d2')
        print(result_2) 

And this is the html code:

<script type="text/javascript">
  function dropdownChange () {
    var selectedRegion = $(".toChange option:selected").val();
    $.ajax({
            url: '/myApp/templates/',
            type: 'POST',
            data: {'d1': selectedRegion},
            }
    }); 
}
$(".toChange").change(dropdownChange);
</script>

  <select name="d1" class="toChange">
    <option val="1"> 1 </option>
    <option val="2"> 2 </option> 
  </select>

 <select name="d2">
    <option val="3"> 3 </option>
    <option val="4"> 4 </option> 
  </select>

When the dropdown d1 faces a change, I want both d1 and d2 values to be sent to my view. The value of d1 is properly captured but d2 (so result_2) shows "[]". How can I capture the two variables?

1 Answers

Simply add it in the data variable:

var selectedRegion = $(".toChange option:selected").val();
var selectedRegion2 = $("select[name=d2] option:selected").val();
$.ajax({
    url: '/myApp/templates/',
    type: 'POST',
    data: {'d1': selectedRegion, 'd2': selectedRegion2},           
}); 
Related