ajax.data: submitting select with multiple option
ajax.data: submitting select with multiple option
Hi!
I am trying to use my own filter form together with Datables search string. To send filter form data I am using ajax.data
option as follows:
"ajax": {
"url": "{{ datatable_url }}",
"data": function (d) {
var formData = $("#filter-form").serializeArray();
for (var i in formData) {
var field = formData[i];
d[field["name"]] = field["value"];
}
return d;
}
}
However, if the form has a select with multiple selection enabled, this approach does not work.
In this case HTML form is usually submitted as: http://your.url/endpoint/?choices=1&choices=2&choices=3&other_field=8
I have tried the following code (that uses lists as dictionary values), but it did not work.
"ajax": {
"url": "{{ datatable_url }}",
"data": function (d) {
var formData = $("#filter-form").serializeArray();
for (var i in formData) {
var field = formData[i];
var existing = d[field["name"]];
if (existing) {
existing.push(field["value"])
d[field["name"]] = existing;
} else {
d[field["name"]] = [field["value"]];
}
}
return d;
}
}
The form is serialized as http://your.url/endpoint/?choices[]=1&choices[]=2&choices[]=3&other_field[]=8
Is it possible to have multiple values with a same key using ajax.data
(or any other) option and without adding brackets? Or I have to do some tricks on the server side to parse this form as simple HTML form?
Answers
This is really a jQuery question, rather than DataTables, but as far as I am aware, no it isn't possible. You might have more luck asking in a jQuery specific forum though.
Allan
Wow, I really did not know that jQuery
$.ajax
function serializes AJAX data with brackets by default. Thanks.After reading jQuery documentation I have found
$.param()
function andtraditional
param.Using the
traditional
param and the fact that Datatables'ajax.data
can return string instead of object I came up with the following solution:Now both Django forms and server side search/order code are happy with request data!
Awesome - thanks for posting back with your solution. Good to hear you've got it working.
Allan