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 (selected_users
-which is working fine upon testing it with alert
function )and then sends them collectively. But I'm not able to post the data. The error that I get is Key 'users' not found in . Where i'm going wrong? how do I modify my POST statement in jQuery plugin?
View.py
def get_data(request):
if request.method == 'POST':
selected_users = request.POST['users']
return HttpResponse(selected_users)
urls.py
urlpatterns = patterns('',
url(r'get_data/','apps.api.views.get_data', name = 'grabhalo_get_data'),
)
jQuery
$(document).ready(function(){
$('#submit').click(function() {
var selected_users = $('input[type=checkbox]:checked').map(function(_, el) {
return $(el).val();
}).get();
alert(selected_users); // works fine
$.post("get_data/",{users:selected_users}); // not able to post
});
})
Checkboxes
{% for user in users %}
<input type="checkbox" class="check" value="{{user.id}}" />{{user.name}}<br>
{%endfor%}
<form id="form" method="POST" action="/get_data/">
{% 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>
Different Suggestions are welcomed , if anyone can redefine the .post function.
Thanks
Why dont you try your POST like this:
try this in your view.py :
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:Please see:
QueryDict.getlist(key, default)
django - getlist()
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
You can use
$.ajax
instead if you want to work with lot more optionsYou just have to combined @Aditya and @Yurly answers:
script
views.py