2

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']}>
0

1 Answer 1

4

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This totally helped me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.