JQuery removes empty arrays when sending

Our organization has two approaches to the problem:

  • Sending data as JSON as opposed to POST-data is a good all-purpose approach, though this is sometimes a little bit difficult to integrate with frameworks like Rails, because you may have to add explicit back-end calls to decode the JSON data.
  • [""] as noted by vinod will work well, as many frameworks (e.g. Rails) will often treat this as an empty array. (for the reason, see this Stack Overflow answer).
    • Note: This works when trying to integrate with some aspects of Rails, specifically when sending a list of ids of objects that are related by a has_many relationship. E.g. if you have a foos table and a bars table, and foos has_many :bars through :foo_bars, a way to remove all associations on a foo object is to pass foo: { bar_ids: [""] }.

Both approaches are hackier than desired, and I would be glad to discover a cleaner approach.


2018, Sorry to answer old question, but here's a better answer IMHO:

var arr = [];

$.post('block_ajax.php', {
    'action': 'set_layout',
    'listid': 123,
    'layout': arr.toString() // It'll be empty string "" if array is empty, otherwise if array has value(s) it will be a string of comma-separated values
}, function(data) {
    // ...
});

Examples:

var layout = [].toString();// layout will be '' (empty string)
var layout = [1,2,3].toString();// layout will be string with comma-separated values '1,2,3' 

In back-end, whether it's empty string or comma-separated string, it will always be posted, just convert it to array.

Back-end (PHP example):

$layout = explode(',', $_POST['layout']);

i think json will help in such a case

encode the array in js and send the result then decode it in php

but this will take some resource