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

jul
  • 36,404
  • 64
  • 191
  • 318

2 Answers2

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'
});
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155