2

i am using jquery to send json data that contains array of elements like this

$('#brand_category').click(function(event){

        category = $("input:checkbox[name=category]:checked").map(function() {
        return this.value;
        }).get();

        brand = $("input[type='radio']:checked").map(function() {
        return this.value;
        }).get();

        parameter.push({
          brand :   brand,
          category: category
        });

        var json = JSON.stringify(parameter)

        $.ajax({
            type: 'post',
            url: "{% url 'seller_details' %}",
            data: {'parameter[]' : json , csrfmiddlewaretoken:'{{csrf_token}}'},
            success: function(data){
            },
            error:function (response, error){
            }
            });

and in the view i am collecting the data like this

brand_category = self.request.POST.get('parameter[]')
print brand_category

this prints the data as this

[{"brand":["spykar"],"category":["Women Clothing","Dresses"]},{"brand":["Madame"],"category":["Women Clothing","Dresses"]}]

then i tried to loop through the json like this

for list in list_data:
                brand =  list_data['brand']
                print brand
                categories = list_data['category']
                print categories

but i am getting the error as this

list indices must be integers, not str

how can i loop through the json data to get the list of brands and categories?

2 Answers 2

2

Your outer loop is a list, and then you loop through each dictionary in the list. Also, you have to convert the string to a python object.

import json
brand_category = self.request.POST.get('parameter[]')
Lbrand_category = json.loads(brand_category)
for D in Lbrand_category:
   brand,categories = D['brand'],D['category']

Note: if you want only the brand string, without the list, use:

brand,categories = D['brand'][0],D['category']
Sign up to request clarification or add additional context in comments.

1 Comment

in the first one it throws string 'indices must be integers'
0

I recommend you this AJAX Request (Its more clear):

$('#brand_category').click( sendAjax );

function sendAjax()
{
  var category = $("input:checkbox[name='category']:checked").val();
  var brand = $("input[type='radio']:checked").val();

  var data = { "category" : category, "brand" : brand, "csrfmiddlewaretoken" : '{{csrf_token}}' }

  $.ajax({
    type: 'post',
    url: "{% url 'seller_details' %}",
    data: data,
    success: function(data)
    {
      //console.log(data) // Print the response of Django or see this in "Network" request, F12 Chrome
    },
    error:function (response, error)
    {
    }
  });
}

View:

category = request.POST['category']
print category

brand    = request.POST['brand']
print brand

List data of brands in JavaScript:

var data = {} //This is a empty object named data
data.brans = [];

and then you need create a for select all brands

for ("list of brands"){
  brand_name = logic
  data.brands.push(brand_name)
} //This is only a idea

6 Comments

How will i come to know that which brand has which category ?
what i am trying to do this a user can select multiple brands and each brand can have multiple categories
well, you miss something in the question. If print brand_category gives you a list, the prev code should have worked, if it's a string, then this one. Tested both
I wanna ask a question...is this a correct way to send data in such a scenario?
Mmmm the category have many brands? See this link
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.