student101
student101

Reputation: 522

Ajax not posting Select Option

I'm trying to get the value of the option in my template below called exampleid. I've followed several examples I found online, but nothing seems to work. My template below has the ajax and jquery to get the value but when I try to print it returns None. I've exhausted my resources and my professor doesn't seem to know, he's "looking into it".

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onchange="accesslevelid" title="">
            <option value="7"> Option 1</option>
            <option value="5"> Option 2</option>
            <option value = "3"> Option 3</option>

</select>
<script>
$(document).ready(function () {
    $('#accesslevelid').on('change', function () {
        var accesslevelid = $(this).val();
        $.ajax({ url: "{% url 'submitted' %}",
                headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                data: {
                  accesslevelid: accesslevelid,
                },
                type: 'POST',
                success: function (result) {
                  alert(result);
                },
              });
      });
  });
</script>

my view attempting to retrieve the value of the post.

exampleidpost = request.POST.get('accesslevelid', False)
print (exampleidpost)

My desired result is for the POST to return a 7,5, or 3.

Upvotes: 0

Views: 52

Answers (1)

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

You should add csrf token to you ajax request, Try this way.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title="accesslevelid" class="form-control" id="accesslevelid" >
    <option value="1"> Option1</option>
    <option value="2"> Option2</option>
    <option value="3"> Option3</option>
</select>

<script>
$(document).ready(function () {
    $('#accesslevelid').on('change', function () {
        var accesslevelid= $(this).val();
        $.ajax({ 
             url: "{% url 'submitted' %}",
             headers: {'X-CSRFToken': '{{ csrf_token }}'},
             data: {
                 accesslevelid: accesslevelid
             },
             type: 'POST',
             success: function (result) {
               alert(result);
             },
        });
    });
});
</script>

And you no longer need a form.

Upvotes: 1

Related Questions