[Answer]-JQuery POST not returning variable users

1๐Ÿ‘

Your JQuery $.post function is ok, the problem is getting the values in a Django view. You are posting an array of values โ€“ to get them you use getlist() function on POST QueryDict. So your view would look like this:

if request.method == 'POST':
    selected_users = request.POST.getlist('users[]')
    return HttpResponse(selected_users)

Please see:

QueryDict.getlist(key, default)

django โ€“ getlist()

๐Ÿ‘คYuriy

0๐Ÿ‘

Why dont you try your POST like this:

$(document).ready(function(){
  $('#submit').click(function() {
      var selected_users=[];
      var $inputs = $('.check');
      $inputs.each(function() {         
            selected_users.push( $(this).val());        
        });            
                    alert(selected_users);     // works fine
      $.post("get_data/",{"users" : selected_users},function(response) 
        {
            alert(response);
        });     
            })

try this in your view.py :

if request.method == 'POST': 
selected_users = request.POST.get("selected_users", "")
return HttpResponse(selected_users)
๐Ÿ‘คAditya

0๐Ÿ‘

You just have to combined @Aditya and @Yurly answers:

script

function get_csrf_token(){
    return $("input[name='csrfmiddlewaretoken']").val();
}

$(document).ready(function(){
    $('#submit').click(function() {
        var datas = new Array();
        var i = 0;
        var csrf_token = get_csrf_token();

        $("input[type=checkbox]:checked").each(function() {
            datas[i] = $(this).val();
            i++;
        });   

        #make sure the url is correct
        $.post("get_data/", {'users[]': datas, 'csrfmiddlewaretoken': csrf_token}, function(data){
            alert(data);
        });   
    });    
})

views.py

if request.method == 'POST':
    selected_users = request.POST.getlist('users[]')
    return HttpResponse(selected_users)
๐Ÿ‘คcatherine

0๐Ÿ‘

When you submit the form you would need to prevent the default action. Otherwise your page refreshes voiding an post from happening.

Also use serialize array to convert them into an array. Try this

$(document).ready(function(){
     $('#submit').click(function(e) {
         e.preventDefault();
         // Will only serialize the checked values by default
         var selected_users = $('input[type=checkbox]').serializeArray();
          console.log(selected_users);     
          $.post("get_data/",{'users[]':selected_users}); 
     });    
})

You can use $.ajax instead if you want to work with lot more options

$.ajax({
     url : 'get_data', 
     data : {'users[]' : selected_users},
     dataType: "set it to the type you are expecting".
     type : 'post'
}).done(function(data, status, xhr) {
   console.log(data)
}).fail(function(xhr, status, error) {
   console.log("Error status : "+ status + "-- error : " + error);
});

Leave a comment