thadeuszlay thadeuszlay - 4 months ago 13
Ajax Question

Query with datatables by passing custom parameters in JavaScript

I try to get data from a database and display it on a datatable. This code works:

tableTest = $('#example').DataTable({
ajax: "/datatables/getSomething",
serverSide: true,
processing: true,
columns: [
{data: 'a'},
{data: 'b'},
{data: 'c'},
{data: 'd'}
],
responsive: true
});


But now I want to pass custom parameters, e.g.
myCustomParams = ["foo", "bar", "top"]
to the request so I can query custom data.

tableTest = $('#example').DataTable({
ajax: {
url: "/datatables/getSomething",
type: "POST",
data: myCustomParams
},
serverSide: true,
processing: true,
columns: [
{data: 'a'},
{data: 'b'},
{data: 'c'},
{data: 'd'}
],
responsive: true
});


In
getSomething()
I would then take the parameters (i.e.
["foo", "bar", "top"]
), query the dataset I want, and then return it back.

But I would only get the error


invalid JSON response.


I looked up that error. I debugged, I looked into Developer Console-> Network-> response and saw that instead of a return value, I get the whole page back. Is there a syntax error I'm missing?

Answer

as per jquery documents the data should be a plain object or string that is sent to the server with the request.

https://api.jquery.com/jquery.post/

you are directly passing an array , try to wrap that inside an object {},

including the example as per the suggestion by OP

 ajax: {
  url: "/datatables/getSomething",
  type: "POST",
  data: { "myRequest": myCustomParams } 
}
Comments