DataTables Odd AJAX Bug
DataTables Odd AJAX Bug
Important! The implications of following problem results in ServerSide processing being inaccessible, making it seemingly impossible to work with large datasets
When passing in $('form').serialize()
for AJAX params, it is breaking up the string and sending each character its own value.
{
ajax: {
url: window.location.pathname, // calling the correct url
data: $('form').serialize(), // am sure this is resolving to a string, like 'key=value&key2=value2'
type: 'POST' // tried GET, JSON, and leaving it blank
},
...
}
So given the serialized example above of key=value&key2=value2
, debugging in Firebug shows DataTables is breaking the string into tokens and sending each as an individual set of arguments to make it look like token index is the key and the characters are the value:
1 k
2 e
3 y
4 =
5 v
...etc
I'm curious if this has anything to do with Rails putting in special form UTF-8 values. The only way I can get this to work is to execute a look up separately using $.ajax()
and creating the datatable in the callback (somewhat assuring me special characters aren't at fault); the following works:
$.ajax({
url: window.location.pathname,
data: $('form').serialize(),
type: 'POST'
success: function(response){
createDataTable( response.data );
}
});
The HTTP request using the jQuery ajax function above works as expected and passes the arguments like so key : value
, key2 : value2
. So why would DataTables break up the string? This leads me to believe there is a bug somewhere, which would render the AJAX functionality useless.
Even Odder
data: $('form').serializeArray()
works, but if I try to store it in a variable and add a parameter to the array, I get funny results in the request. An example of doing this is:
var form_data = $('form').serializeArray();
form_data.push({ 'name' : 'dynamic_param', 'value' : 'dynamic_param_value' });
// DataTable({ ajax : { ..., data: form_data }, ...)
Now in the debugger the parameters look like this, notice it's back to using the index, but has also started using the object property as the HTTP param key:
0[name] key
0[value] value
1[name] key2
1[value] value2
2[name] dynamic_param
2[value] dynamic_param_value
To make sure there's nothing wrong with the form, calling the same from $.ajax()
still formats the request params as expected:
key value
key2 value2
dynamic_param dynamic_param_value
Answers
I created an issue in github at:
https://github.com/DataTables/DataTables/issues/490#issue-56606852
I found that I was passing in a datatype that DataTables didn't expect and there isn't any odd issue with DataTables. Allan has graciously mentioned that he'd update the documentation in a couple places.
I was trying to pass in a string, or array of objects, which
.serialize()
and.serializeArray()
return from serializing a form; however, DataTables only accepts one object, which it accepts it's key/value pairs from.