简体   繁体   中英

Django: can't retrieve variable from my view after AJAX call

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?

You are missing the URL and the success callback in the Ajax call. You could get the response in the success Callback.

You are getting null in alert because the $.ajax is an async function and alert will appear before the ajax call can complete.

Try the below example.

Example:

 <script type="text/javascript">
    function dropdownChange () {
      var selectedValue = $(".toChange option:selected").val();
      $.ajax({
              url: "<add the url>"
              type: 'POST',
              data: {'myVal': selectedValue},
              success: function(res) {
                alert(res);
              }
        });       
    }
    $(".toChange").change(dropdownChange);
  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM