Erik Åsland
Erik Åsland

Reputation: 9782

How to send object that contains array via AJAX POST in Django

I am trying to send a object with an array inside of it via an AJAX POST in Django when the user clicks a button. I am following the instructions on the Django docs have hit a snag. I am attempting to see a specific indice in the array using logger.debug() in the view and am not able to access the contents. How do I access that specific element in the array?

My AJAX...

var tags_selected = [1,2,3,4]

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

$("#filter").click(function(){
  $.ajax({
    type: 'POST',
    url: "/pensieve/filtertags",
    data: {'tags': tags_selected},
    success: function(res){
      console.log(res)
    },
    dataType: "json"
  });
})

My View...

def filter_tags(request):
    logger.debug(request.POST)
    return HttpResponse(json.dumps({'response': 111}), content_type="application/json")

My DEBUG log in my terminal...

DEBUG - 2016-05-06:17:15:50 - <QueryDict: {u'tags[]': [u'142', u'122', u'138']}>

Upvotes: 2

Views: 1319

Answers (1)

Louis Barranqueiro
Louis Barranqueiro

Reputation: 10228

You can get values of the tags[] Array with getlist() method.

Example :

request.POST.getlist('tags[]')
# outputs : ['1', '2', '3']
request.POST.getlist('tags[]')[1]
# outputs : '2'

Upvotes: 4

Related Questions