2

Below is the code I am using in my html to send an array of userids(numbers). On click of the checkboxes I am sending the array (checkIds):-

var checkIds = []
           $(document).on("click","#group_save",function(){
               $("#candidate-data tr").each(function(index,rowhtml){
                  var checked= $('input[id="groups"]:checked',rowhtml).length;
                  checkIds = jQuery.unique(checkIds)
                  if (checked==1){
                    checkIds.push($('.hideMe',rowhtml).text());
                  }
                });
               alert(checkIds);
               var jsonText = JSON.stringify(checkIds)
               checkIds.length = 0;
               var groupName = $('input:text[name="group_name"]').val();
               alert(groupName)
               $.ajax({
                    url: "{% url 'userinfo:groups' %}" + "?gname="+groupName,
                    type: "POST",
                    data:jsonText,
                    dataType: 'json',
                    success: function(){
                        notyfy({type: "success", layout: "topCenter", text: "Saved", timeout: 5000});
                    }
               });
           });

How do I access the data:jsonText in my views. py I am doing this way which does not work I have to save the gname(name) along with the array(jsonText) ids in two tables Groups and GroupMembers in groups table i have to save group name(gname) and after saving i have to get the id of the saved group object and along with the array of userids(jsonText) have to be saved in GroupMembers table:-

def groups(request):
    gname = request.GET.get('gname', None)
    if request.method == 'POST':
        Groups(name=gname).save()
        usersV = request.POST.get('jsonText')
        x = request.GET.get('id',None)
        print x
        if x != "0":
            for users in usersV:
                print users
                GroupMembers(group_id=x,user_id=users).save()
        return HttpResponse("Success")
    else:
        return HttpResponse("Error")
Akherus
  • 51
  • 1
  • 6

4 Answers4

3

This worked for me :

 var checkIds = [];
        $(document).on("click","#group_save",function(){
          $("#candidate-data tr").each(function(index,rowhtml){
            var checked= $('input[id="groups"]:checked',rowhtml).length;
            checkIds = jQuery.unique(checkIds)
            if (checked==1){
              checkIds.push($('.hideMe',rowhtml).text());
            }
          });
          alert(checkIds);
          var groupName = $('input:text[name="group_name"]').val();
          alert(groupName);
            $.ajax({
                url: "{% url 'userinfo:groups' %}" + "?gname="+groupName+"&checkids="+checkIds,
                type: "POST",
                dataType: 'json',
                traditional: true,
                success: function(){
                        notyfy({type: "success", layout: "topCenter", text: "Saved", timeout: 5000});
                    }
            });
            checkIds.length = 0;

and in your views.py:

def groups(request):
    print request.GET.copy()
    gname = request.GET.get('gname', None)
    if request.method == 'POST':
        g = Groups(name=gname)
        g.save()
        x = g.pk
        userlist = request.GET.get('checkids')
        for users in userlist:
            print users
            GroupMembers(group_id=x, user_id=users).save()
        return HttpResponse("Success")
    else:
        return HttpResponse("Error")
Pedram Parsian
  • 3,750
  • 3
  • 19
  • 34
Akherus
  • 51
  • 1
  • 6
1

You should be able to use the following:

var checkIds = [];
$(document).on("click","#group_save",function(){
  $("#candidate-data tr").each(function(index,rowhtml){
    var checked= $('input[id="groups"]:checked',rowhtml).length;
    checkIds = jQuery.unique(checkIds)
    if (checked==1){
      checkIds.push($('.hideMe',rowhtml).text());
    }
  });
  var groupName = $('input:text[name="group_name"]').val();
  $.ajax({
    url: "{% url 'userinfo:groups' %}",
    type: "POST",
    data: {
      "gname": gname,
      "checkids": checkIds.slice(0)
    },
    dataType: 'json',
    traditional: true,
    success: function(){
      notyfy({
        type: "success", 
        layout: "topCenter", 
        text: "Saved", 
        timeout: 5000
      });
    }
  });
  checkIds.length = 0;
});

Then on your python side just use:

request.POST.get('gname');
request.POST.getlist('checkids');


a short explanation

First off jQuery handles the conversion of a data object for you, so there is no real need to preprocess it with JSON.stringify or anything else, unless you are sending a very specific format to the server. By setting the traditional: true you are asking jQuery to convert your array parameters using the following format:

checkids=value&checkids=value&checkids=value

Rather than:

checkids[]=value&checkids[]=value&checkids[]=value

This is explained well here and here but the long and short of it is that python/django support the "non square bracket" form of param serialization out of the box using .getlist().

Oh and the reason for the checkIds.slice(0) (which creates a copy of the array) is just because you are setting checkIds.length = 0; later and the paranoia in my head is telling me that if the ajax call fires in a later execution cycle the array would be empty if I had used a direct reference rather than a copy. This is extremely unlikely, as the ajax call should be triggered the moment it is requested, but I always err on the side of caution when dealing with black-boxes or libraries like jQuery... you should by no means pander to my paranoia though and can very probably safely use:

    data: {
      "gname": gname,
      "checkids": checkIds
    },
Community
  • 1
  • 1
Pebbl
  • 34,937
  • 6
  • 62
  • 64
  • But its showing checkIds length as zero there are no elements in the array.Please help me Thank you Pebbl – Akherus Jun 06 '14 at 05:36
  • @user3710945 ~ where abouts is it showing `checkIds` length as zero? is it before the ajax call? or on the django/python side? If it's before the ajax call then we need to investigate your jQuery for collecting the checkIds, if on the Django side you need to be using `checkids` all lower case (at least in terms of my answer above). Obviously if you are checking after the ajax call the `checkIds.length = 0` will be the problem. – Pebbl Jun 06 '14 at 07:15
  • its on django python side when i debug code in pycharm i find checkids length zero even if i remove the line checkids.length = 0; – Akherus Jun 07 '14 at 08:09
  • @user3710945 ~ If you update your question with the latest code you are using in your `def groups` and at the the top of `def groups` add `print request.GET.copy()` and add that output to your question it will help debug the problem. – Pebbl Jun 07 '14 at 09:28
0

jsonText is the the name of the variable you use in the js file to describe the JSON. It is not the name of the key to some data in the JSON structure. In the line below replace jsonText with the actual key name.

request.POST.get('jsonText')
Rebecca Meritz
  • 722
  • 1
  • 5
  • 15
0

The request.POST dict is for form-encoded values. You're not sending those: you're sending a single JSON blob. You can use request.body to get that JSON, and then parse it to get a Python dict.

usersV = json.loads(request.body)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895