0

I'm passing an array from form inputs (checkboxes) using the get method. When doing in ajax, with:

var subcat_checked = new Array();
$.each($("input[name='subcategories']:checked"), function() {
    subcat_checked.push($(this).val());
});
$.ajax({
    type: 'GET',
    url: '{% url view-category root_category.slug %}',
    data: {subcat: subcat_checked},
    success: function(result) {
        /* stuff */
    },
    dataType: 'json'
});

the variable key is 'subcategories' when no checkbox is checked, and 'subcategories[]' when some are checked.

Now, when sending it using a non-ajax form and some checkboxes are checked, the variable key is 'categories' (with no [] at the end).

Since I'd like to use the non-ajax form as a fallback if javascript is disabled, I'd like to have the same key when some checkboxes are checked.

Anybody knows how I can do that?

Thanks

1

2 Answers 2

0

This was a change made in jQuery 1.4+, but you can reverse it with the traditional option to get the old non-[] serialization, like this:

$.ajax({
    traditional: true,
    type: 'GET',
    url: '{% url view-category root_category.slug %}',
    data: {subcat: subcat_checked},
    success: function(result) {
        /* stuff */
    },
    dataType: 'json'
});

You can read more about the option in the $.param() docs (what's ultimately called when passing an object as your data property)....but basically it does exactly what you want, leaving the [] off.

Sign up to request clarification or add additional context in comments.

Comments

0

try this:

var subcat_checked = $("input[name='subcategories']:checked").serializeArray();

$.ajax({
    type: 'GET',
    url: '{% url view-category root_category.slug %}',
    data: {subcat: subcat_checked},
    success: function(result) {
        /* stuff */
    },
    dataType: 'json'
});

Comments

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.