简体   繁体   中英

How to post data to API in jQuery DataTable ajax?

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 ie 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

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 (ie 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}
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM