Yunti
Yunti

Reputation: 7458

django ajax, can't capture a list from get ajax request

I'm trying to capture a list of filters in an ajax request, but although I can capture a single filter, when I try to capture a list, I just get an empty list for some reason. Below is the relevant part of my view and the ajax (jQuery) function. When I try and send a single filter with $.ajax({ .... 'filters': fixed }) this works but fails with a list.

Update: trying data: {'filters': JSON.stringify([fixed])}, does pass the data through as a string to django '["fixed"]' (which I can handle if I don't use getlist but .get and then json.loads() but I think there must be a simpler method here.

def quotes_results_filter_view(request):
    results_filters = request.GET.getlist('filters') or []
    quotes_results = request.session['quotes_results']
    for results_filter in results_filters:
      .......

Ajax function:

$(document).ready(function () {
      $('#id_filter').change(function (e) {
        var fixed = $(this).val()
        console.log(fixed)
    $.ajax({
      url: '/users/filters/',
      data: {
        'filters': [fixed]
      },
      dataType: 'json',
      success: function (data) {
        console.log(data)
      }
    })

Upvotes: 0

Views: 139

Answers (1)

pedrotorres
pedrotorres

Reputation: 1232

When you send a list through jQuery it changes the keyword to so in Django you probably have to get like this: request.GET.getlist('filters[]')

Upvotes: 2

Related Questions