I am trying to pass a variable via Ajax to the retrieve data to fill a DataTable. I'm yet to find an explanation as to why, but my Ajax payload is resulting in a strange encoding with a combination %
and =
symbols along with some random characters. I've played around with the contentType and the way in which I use the JSON.stringify() but neither correct the unexpected output I am experiencing.
Javascript Ajax request:
var group = { groupId: 123456789 }
...
"ajax": {
type: 'POST',
url: window.SiteRootURL + 'Group/GetGroup',
contentType: 'application/json',
data: JSON.stringify(group),
"error": function (xhr, error, thrown) {
notfiy({ status: "Error", message: thrown }, 'error');
}
Controller:
public ActionResult GetGroup(Int32 groupId)
{
// do something
}
Ajax Request Payload:
0=%7B&1=%22&2=g&3=r&4=o&5=u&6=p&7=A&8=r&9=t&10=i&11=f&12=a&13=c&14=t&15=I&16=d&17=%22&18=%3A&19=1&20=2&21=3&22=4&23=5&24=6&25=7&26=8&27=9&28=%7D
Expected Ajax Request Payload:
{groupId: 123456789}
Any help appreciated :)
The issue is directly related to DataTables. In the Ajax request, ajax.data
does not accept a string. In order to post JSON data you must return the string in a function. The below is an example from the documentation:
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"contentType": "application/json",
"type": "POST",
"data": function ( d ) {
return JSON.stringify( d );
}
}
} );