Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery removes empty arrays when sending

Tags:

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?

like image 496
Martijn van der Lee Avatar asked Jul 08 '11 09:07

Martijn van der Lee


3 Answers

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.

like image 185
Luke Knepper Avatar answered Oct 05 '22 18:10

Luke Knepper


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']);
like image 32
evilReiko Avatar answered Oct 05 '22 16:10

evilReiko


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

like image 42
Robert Avatar answered Oct 05 '22 18:10

Robert