I am trying to post the values of checked boxes, but unable to do so. It first collects all the checked boxes in an array (datas
-which is working fine upon testing it with console.log(datas)
) and then sends them collectively. But I'm not able to post the data. I'm getting an empty array. Where I'm going wrong?
views.py
if request.method == 'POST':
selected_users = request.POST.getlist('users[]')
return HttpResponse(selected_users)
jQuery
$(document).ready(function(){
$('#submit').click(function() {
var datas = new Array();
var i = 0;
$("input[type=checkbox]:checked").each(function() {
datas[i] = $(this).val();
i++;
});
console.log(datas) //works fine
$.post("get_data/", {'users[]': datas}, function(data){
alert(data);
});
});
})
urls.py
urlpatterns = patterns('',
url(r'get_data/','apps.api.views.get_data', name = 'grabhalo_get_data'),
)
Checkboxes
{% for user in users %}
<input type="checkbox" class="check" value="{{user.id}}" />{{user.name}}<br>
{%endfor%}
<form id="form" method="POST" action="#">
{% csrf_token %}
<input type="text" class="span8 search-query" placeholder="Type here..." name="chat">
<input type="submit" value="Send" class = "btn btn-primary" id = "submit">
</form>
Here are the parameters while viewing console.log
users[] 1
users[] 2
I'm guess there is some bug in views.py, though not sure. Kindly help me rectify the same.
1. Missing prevent default
replace:
with:
2. Missing name for checkboxes