JQuery removes empty arrays when sending

Viewed 19498

I have the following code:

$.post('block_ajax.php'
    ,   {   'action': 'set_layout'
        ,   'listid': 123
        ,   'layout': []
        }
    ,   function(data) {
            // ...
        }
);

The recieving script (block_ajax.php) only recieves the "action" and "listid" parameters. When I inspect what is sent using Chrome, I see the "layout" parameter isn't even send to the backend script.

Since there is a difference between an empty array and the absence of an array, I'd like to have JQuery send the empty array. I can find some indications that JQuery (1.6.1) seems to do this, but not how to stop it from doing so. JSON format allows for empty arrays and empty objects, so I think it should be possible.

Does anybody know what to change so JQuery can send empty arrays?

7 Answers

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 solved this the following way, which I feel is easiest to read. Supposing there's an array myArray which could be populated or empty:

'requestParam': myArray.length === 0 ? '' : myArray

Even when empty, jQuery will not omit the requestParam argument.

I found a simple cheat that works

$.post('block_ajax.php'
    ,   {   'action': 'set_layout'
        ,   'listid': 123
        ,   'layout': [{}]
        }
    ,   function(data) {
            // ...
        }
);

Notice I defined the empty array as [{}]. The jQuery ajax command just sends an empty array without the empty object.

NOTE: [[]] does not work.

Related