Hannan
Hannan

Reputation: 1191

Django / Ajax - How to filter and display result based on selection

I am trying to filter and display data in Django based on the selection made by the user from drop down box. I'm using ajax call to send a request to Django views. When a user selects, for example, Airline A, then Ajax will send the 'value' of that selection which is an integer to Django backend to filter data and send it back to frontend. Here is my code:

HTML:

<form method="GET">
    <select id="airline-selected">
        {% for airline in airline_list %}
            <option value="{{ airline.id }}">
            {{ airline.name }}
            </option>
        {% endfor %}
    </select>
    <input type="button" value="Update" id="selection-button" method="GET">
</form>

Ajax:

<script>
        $( "#selection-button" ).click(function(event) {
            event.preventDefault();
            var airlineSelected = $('#airline-selected').find(":selected").val();

            $.ajax({
                url: "{% url 'charts_data' %}",
                method: 'GET',
                filter_category: parseInt(airlineSelected),
                success: function(data){
                console.log(data)
         },
                error: function(error_data){
                console.log("error")
                console.log(error_data)
         }
            })
        });
    </script>

Views.py:

class ChartData(generics.ListAPIView):
    serializer_class = FinancialDataSerializer

    def get_queryset(self, *args, **kwargs):
        filter_category = self.request.GET.get("filter_category")
        queryset = FinancialData.objects.filter(airline_id=filter_category)
        queryset_filtered = queryset.filter()
        return queryset_filtered

My console.log(data) is showing an empty Array which means views are not getting filtered. How can I filter and display the data based on the selection made by the user?

Upvotes: 5

Views: 11507

Answers (1)

badiya
badiya

Reputation: 2257

try to modify your ajax code to add a data variable.

$.ajax({
     url: "{% url 'charts_data' %}",
     method: 'GET',
     data : {
             filter_category: parseInt(airlineSelected)
     }
     success: function(data){
         console.log(data)
     },
     error: function(xhr, errmsg, err){
         console.log("error")
         console.log(error_data)
     }
});

Upvotes: 7

Related Questions