ChipNugget
ChipNugget

Reputation: 383

How to access the ajax.data object for server-side processing (jquery DataTables)?

I've seen https://datatables.net/reference/option/ajax.data and other examples on how to send custom HTTP variables to the server. But I'm having trouble understanding how to send the object as an parameter. I want to be able to view all the parameters the DataTable sends to the server as an object rather than individual parameters.

My setup is as follows:

$(document).ready(function () {
$('#example').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
        "url": '/Browse/GetRecordsAsync',
        "type": 'POST',
        "datatype": "json",
        "data": {
            "sentData": $.ajax.data,
            "search": "asd"
        }
    },
    columns: [
        { "data": "name"},
        { "data": "occupation"},
        { "data": "salary"},
    ],
    });
});

In my controller, the signature of my controller action is:

[HTTPPost]
public async Task<ActionResult> GetRecordsAsync(object sentData, int draw, int start, int length, string search)

This was a simple experiment to see what data is being sent to the server. I am not sure how to get the returned object (documentation states ajax.data option sends this info) and how to set up the method signature to properly access that object. Also, I am not sure how to setup the method parameters to access search[value] or order[i][column] from https://datatables.net/manual/server-side#Returned-data

I'm reading the documentation and I still don't understand how to access the returned object or the specific parameters like search[value] from my controller.

Upvotes: 1

Views: 2987

Answers (2)

DKATyler
DKATyler

Reputation: 971

I had the same question, and could only find this which says the object isn't public: https://datatables.net/forums/discussion/25470

However, you can mimic the functionality, the below was written for DataTables 1.10.18:

//This function returns the ajax post object datatables generates automatically on refresh
function GetDataTablePost(dt) {
    //Originally Sourced from: https://datatables.net/forums/discussion/21940/how-to-pass-new-post-parameters-on-ajax-reload
    //Modified heavily to make something postable.
    var settings = $(dt).dataTable().fnSettings();

    var obj = {
        //default params
        "draw": settings.iDraw,
        "start": settings._iDisplayStart,
        "length": settings._iDisplayLength
    };
    //columns
    for (var index in settings.aoColumns) {
        obj['columns[' + index + '][data]'] = settings.aoColumns[index].data;
        //Strictly speaking, this should be settings.aoColumns[index].name, however, using the th value because it's more relevant on a server post.
        obj['columns[' + index + '][name]'] = settings.aoColumns[index].sTitle.trim();
        obj['columns[' + index + '][searchable]'] = settings.aoColumns[index].bSearchable;
        obj['columns[' + index + '][orderable]'] = settings.aoColumns[index].bSortable;
        obj['columns[' + index + '][search]'] = null; //TODO: Populate this correctly.
    }
    //sort
    for (var index in settings.aLastSort) {
        obj['order[' + index + '][column]'] = settings.aLastSort[index].col;
        obj['order[' + index + '][dir]'] = settings.aLastSort[index].dir;
    };
    obj['search[value]'] = settings.oPreviousSearch[settings.oPreviousSearch._hungarianMap['search']];
    obj['search[regex]'] = settings.oPreviousSearch[settings.oPreviousSearch._hungarianMap['regex']];
    settings.ajax.data(obj);
    //Not part of the normal object, add the ajax url for convenience.
    obj['url'] = settings.ajax.url;
    return obj;
}

//This function performs a post containing the parameters in obj.
function doPost(postUrl, obj) {
    //Inspired by: https://stackoverflow.com/questions/1350917/send-post-variable-with-javascript
    var submitMe = document.createElement("form");
    submitMe.action = postUrl;
    submitMe.method = "post";
    submitMe.enctype = "multipart/form-data";
    for (var index in obj) {
        var submitMeInput = document.createElement('INPUT');
        submitMeInput.name = index;
        submitMeInput.setAttribute('value', obj[index]);
        submitMe.append(submitMeInput);
    }
    $(submitMe).hide();
    document.body.append(submitMe);
    submitMe.submit();
    document.body.removeChild(submitMe);
}

To use, my buttons action object is:

action: function (e, dt, node, config) {
    var obj = GetDataTablePost(dt.context[0].oInstance);
    obj.cmd = "Do more stuff!";
    doPost(obj.url, obj);
}

On the server side, I retrieve the parameters with this:

public ActionResult _PopulateDataTable(string cmd, int draw, int start, int length, Dictionary<string, Dictionary<string, string>> columns, Dictionary<string, Dictionary<string, string>> order, Dictionary<string, string> search) {
  int recordsTotal, recordsFiltered;
  var data = applicationData.RunQuery(start, length, columns[order["0"]["column"]]["data"], order["0"]["dir"], search["value"], out recordsTotal, out recordsFiltered);
  return Json(new { draw = draw, recordsFiltered = recordsFiltered, recordsTotal = recordsTotal, data = data });
}

Upvotes: 1

user10217446
user10217446

Reputation: 16

When you set server-side option true, i recommend you add "contentType: 'application/json'" in ajax and the data option in ajax should be a function with a parameter data.

$("#example").DataTable({
        autoWidth: true,
        processing: true,
        serverSide: true,
        ajax: {
            url: "xxx",
            type: "post",
            contentType: "application/json",
            data: function (d) {
                // d.search = $("#search").val();
                console.log(d);  // this a your need
                return JSON.stringify(d);
            }
        }
});

the response object have four property as blow:

- draw: From ajax.data.draw
- data: The data that table need to display
- recordsFiltered: The number after the filter
- recordsTotal: The number before the filter

Upvotes: 0

Related Questions