payal arora payal arora - 3 months ago 8
Javascript Question

Unable to store results using ajax

I am trying to get the results using ajax like this

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

category = $("input[name='category']:checked").data("id");
var Html = "";

$.ajax({
type: "POST",
data: {
'csrfmiddlewaretoken': '{{csrf_token}}',
category: category
},
url: "{% url 'data_entry' %}",
success: function(data) {

console.log(data);

$.each(data, function(key, object) {
$.each(object, function(key, values) {
Html = "<div><label>" + object + "</label>"
$.each(values, function(key, value) {
Html += "<div style='float:left'><input name='" + value + "' type='checkbox' value='" + value + "'><span>" + value + "</span></div>"
});
});
});

console.log(Html)
$('#attribute').html(Html)
},
error: function(response, error) {}
});
});


the results i get is an array that looks like this

[Object, Object]
0
:
Object
color
:
Array[3]
0
:
"BLUE"
1
:
"RED"
2
:
"YELLOW"
length
:
3
__proto__
:
Array[0]
__proto__
:
Object
1
:
Object
size
:
Array[6]
0
:
"S"
1
:
"M"
2
:
"L"
3
:
"XL"
4
:
"XXL"
5
:
"XXXL"
length
:
6
__proto__
:
Array[0]
__proto__
:
Object
length
:
2
__proto__
:
Array[0]


i am trying to loop through all the values of the array and store it in the variable Html but it shows only the final iteration value ie the values present in size array.what can be wrong and how can i resolve this error.

Answer

You're resetting the variable every time you do this:

Html = "<div><label>"+object+"</label>"

So it's only ever going to have the values from the last iteration of the (outer) loop. It sounds like you meant to append rather than assign:

Html += "<div><label>"+object+"</label>"
Comments