jQuery Post data not working

291 Views Asked by At

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.

2

There are 2 best solutions below

2
On

1. Missing prevent default

replace:

$('#submit').click(function() {

with:

$('#submit').click(function(e) {
   e.preventDefault();

2. Missing name for checkboxes

<input type="checkbox" name="..."
5
On

What you are trying could be achived easily with slight code rearranging

Checkboxes

<form id="form" method="POST" action="#">
    {% for user in users %}
    <input type="checkbox" class="check" name='users' value="{{user.id}}" />{{user.name}}<br>    
    {% endfor %}

    {% 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>

jQuery

$(document).ready(function(){
    $('#form').submit(function(evt) {
        evt.preventDefault();

        $.post("get_data/", $(this).serialize(), function(data){
            alert(data);
        });   
    });    
})

See docs on jQuery.serialize() and especially note

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

views.py

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