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?
Our organization has two approaches to the problem:
[""]
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With