Aditya Singh
Aditya Singh

Reputation: 970

Array in jquery retains old data even after ajax submit

I have a list of brands and categories. One brand can have multiple categories.

{% for brand in brands %}
    <li><input type="radio" value="{{brand.title}}" name="brand">{{brand.title}}</li>
{% endfor %}

{% for category in categories %}
    <li><input type="checkbox" value="{{category.title}}" name="category" > {{category.title}}</li>
{% endfor %}

<input type="submit" value="submit" id="brand_category">
<script>
 var parameter = [];
  var brand = [];
  var category = [];

    $('#brand_category').click(function(event) {
        $("input:checkbox[name=category]:checked").each(function(){
            if ($(this).prop("checked", true)) {
                category.push($(this).val())
            }
        });
        parameter.push({
            brand :   $("input[type='radio']:checked").val(),
            category: category
        })
        var json = JSON.stringify(parameter);

        $.ajax({        
            type: "post",
            url: "{% url 'seller_details' %}",
            data: { 
                'parameter[]' : json , 
                csrfmiddlewaretoken: '{{csrf_token}}'
            },
            contentType: 'application/json; charset=utf-8',
            dataType:"json",
            success: function(data) {
                $('#loading-image').hide();
            },
            error: function(response, error) { }
        });
    });

</script>

I tried to send brand and category from the above script but it retains old data in the arrays brand, category and parameter. Is this the correct way to send data for the above scenario?

Upvotes: 0

Views: 136

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337610

It sounds like you're defining the category array outside of the click handler and you're not clearing it's values between clicks. Also note that the if statement in the each block is redundant as the selector is only retrieving elements which are checked.

To solve the issue you can either change the code so that the array is defined inside the handler:

$('#brand_category').click(function(event) {
    var category = [];
    $("input:checkbox[name=category]:checked").each(function(){
        category.push($(this).val());
    });

    // rest of your code...
});

Alternatively you can generate the array from scratch on each click:

var category = [];
$('#brand_category').click(function(event) {
    category = $("input:checkbox[name=category]:checked").map(function() {
        return this.value;
    }).get();

    // rest of your code...
});

Upvotes: 1

Related Questions