Home > Blockchain >  How to post data to API in jQuery DataTable ajax?
How to post data to API in jQuery DataTable ajax?

Time:04-29

Hi all I am using jQuery DataTable and performing server-side pagination and sorting. I am stuck at one place, I am having API that is of type POST, so I need to send my payload in Body.

I tried POST method in ajax but it kept throwing 415 status code i.e payload format is in an unsupported format. I have noticed that my payload is getting sent in form data. How can I resolve this issue?

Here is my code -

$(document).ready(function () {
    $('#dataTable').DataTable({
        columns: [
            { "data": "FirstName" },
            { "data": "LastName" },
            { "data": "PhoneNumber" },
            { "data": "Address1" },
            { "data": "Email" },
            { "data": "Fax" },
            { "data": "Calls" },
            { "data": "Address2" },
            { "data": "Deal status" },
            { "data": "Conversations" }
        ],
        "processing": true,
        "serverSide": true,
        "ajax":{
            "url": "myAPI",
            "dataType": 'application/json',
            "type": "POST",
            "beforeSend": function(xhr) {
                xhr.setRequestHeader("Authorization", "Bearer Token");
            },
            "data": function (d) {
                d.status= "Active";
                d.field = "";
                d.order="asc";
            },
            dataFilter: function(data) {
                var json = jQuery.parseJSON( data );
                json.recordsTotal = json.totalElements;
                json.recordsFiltered = json.totalElements;
                json.data = json.content;
                console.log("total data",json);
                return JSON.stringify( json ); // return JSON string
            }
        }
    });
});

How can I resolve this 415 status code and send payload correctly? Please Help

CodePudding user response:

You are non returning anything from the:

"data": function (d) {
    d.status = "Active";
    d.field = "";
    d.order = "asc";
},

so, according to the docs for the ajax.data option:

If there is no return value from the function (i.e. undefined) then the original data object passed into the function by DataTables will be used for the request (the function may have manipulated its values).

If an object is returned, then that object will be used as the data for the request. It will not be merged with the original data object constructed by DataTables before being sent.

Try:

"data": function (d) {
    const extraPayload = {};
    extraPayload.status= "Active";
    extraPayload.field = "";
    extraPayload.order="asc";

    return {...d, ...extraPayload}
},
  • Related