jqueryajaxarraysobject

JQuery removes empty arrays when sending


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?


Solution

  • EDIT: See Luke's answer for a better solution: https://stackoverflow.com/a/31996181/827437

    I've left my previous answer specific to how Rails handles [""] below, as the link above explains.


    Note: Rails-specific

    I am not sure why you need to send a blank parameter. Merely checking the existence of the parameter in the PHP script should be enough. However, if you really want to do it, use 'layout': [""] instead of 'layout': []. The parameter should be sent.

    (In addition, you might want to rename layout to layout[] to indicate it's an array, but this is unnecessary.)