serverSide ajax function 'data' param sending '[object Object]' in the request

serverSide ajax function 'data' param sending '[object Object]' in the request

DennyJoDennyJo Posts: 2Questions: 1Answers: 0

Description of problem: (We are changing from using clientSide to serverSide processing)
Using serverSide true, I can retrieve the DataSource using Ajax. The following requirements are what the table needs to include, but does not currently work:
- Searching/Filtering
- Sorting by column
- Displaying Total row count, with current page count (e.g '0-10 of 20 results')

For this, the Ajax 'function' (https://datatables.net/reference/option/ajax) is required to pass the Datatables settings into my ajax resource (In this case, Java REST resource).

DataTable({
            serverSide: true,
            select: 'single',
            lengthMenu: [[10, 50, 100, 500], [10, 50, 100, 500]],
            ajax: function (data, callback, settings){
                callback(
                    {"data":[]}
                );
            },
// render/language parts ommitted, just showing the ajax: param
});

'data' in the function() contains the current Datatables info as stated in the docs (such as length, search, etc) but not all values are being sent to the request as expected.

I can filter page size and select a specific page using serverSide with 'length' and 'start', as this gets passed through correctly, but other options get passed in as '[object Object]' as below:

order=[object Object]&start=10&length=10&search=[object Object]

Is there a way that serverSide handles the data differently, or perhaps even a way to retrieve the current config (search/order) so I can stringify the object array and append it onto the ajax request? (I have tried https://datatables.net/reference/api/order() and stringified the value, appending on to the request, but the updated order is not passed through for future renders/changing page)

The Previous/Next buttons are also not working when switching to serverSide, is there a specific doc page for handling these buttons (as the numbered pages send the correct data to the request)

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin

    I don't see how you are actually passing the data parameter to the server there, but you probably need to do JSON.stringify(data). If you can show me how are are using the data object, I will hopefully be able to help a little more.

    Allan

  • DennyJoDennyJo Posts: 2Questions: 1Answers: 0

    Hi Allan,
    Figured it out over the weekend.
    Yes, 'data' (or any specific config i required' needed to be stringified - that solved my [object Object] problem.
    The dataSource was returning 'totalRecords' not 'recordsTotal'. Changing this fixed my paging problem.

    I'm still unable to sort columns. To clarify, if serverSide is enabled, we have to manually order our data using the provided order (column and direction)?

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    edited August 2021 Answer ✓

    we have to manually order our data using the provided order (column and direction)?

    Correct - the server needs to do all the sorting, filtering and paging. That is basically the whole point of server-side processing.

    Allan

  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0

    It would be quite helpful if a code sample was published to help those of us struggling with this. I have no idea what/how/where to stringify the request parameters such as columns, search, order, etc. I would assume that DataTables does this when setting serverSide = true but apparently not. How do I get DataTables to send that as a JSON string to the server? Please, some code examples if at all possible.

  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0

    After searching through the rest of the forums, putting this in my code resolved the issue, but I have yet to see if this has an impact on all of the other ajax-related frameworks implemented. I think it a good idea if there is a way to have DataTables stringify those request parameters as an option at least to prevent dependency on a global setting which could have adverse effects elsewhere outside of DataTables.

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    Ue the ajax.data option for this. See the last example in the docs.

    Kevin

  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0
    edited April 2022

    Thanks, Kevin. I love DataTables, but I find myself constantly digging deep through documentation, forums, and blogs to piece together a solution to what seems should be default behavior or at least common implementation. For those that find themselves here, what Kevin posted:

        $('#example').dataTable( {
            "ajax": {
              "url": "data.json",
              "contentType": "application/json",
              "type": "POST",
              "data": function ( d ) {
                return JSON.stringify( d );
              }
            }
        } );
    
  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0
    edited April 2022

    Well, the frustration continues. Here is my ajax implementation which works fine on the initial load:

              `ajax: {
            url: gridObj.url,
            dataType: "json",
            contentType: 'application/json',
            dataSrc: "gridModel",
            type: "POST",
                    data: function (d) {
                return JSON.stringify( d );
             }                
        }`
    

    The data sent to the server is in proper JSON format. However, when I click on the next page (the numbered button does NOT work), the data sent looks like this including the dreaded "[object, Object]" as well as the html now being escaped. This is entirely maddening. Why is this so difficult to implement and not functioning correctly as default behavior?

    draw=4&columns=%5Bobject%20Object%5D&columns=%5Bobject%20Object%5D&columns=%5Bobject%20Object%5D&columns=%5Bobject%20Object%5D&co

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    Where are you seeing the [object, Object]. Are you seeing this in the request parameters using the browser's network inspector tool or somewhere else?

    I put together this simple example and JSON.stringify( d ) seems to work for multiple pages.
    http://live.datatables.net/merosayo/1/edit

    Unfortunately there isn't Datatables JS BIN server environment that supports JSON data. The best I can do quickly is to use console.log.

    I would start by debugging the ajax.data function to see what d and what JSON.stringify( d ) are when the issue occurs. d should be a standard Javascript object and JSON.stringify( d ) is a standard Javascript function to JSON encode the object. Let us know what you find and what you find in the browser's network inspector.

    Can you post a link to your page or a test case showing the issue so we can take a look?
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0

    Thanks for the quick reply. I will review your testcase and carefully compare to what we are doing. If you prefer, I can take this offline as a support request/ticket (are have a license) and post a relevant solution here when fixed.

    I am going to put together a testcase, but it is pretty complex involving server calls and a complex implementation of DataTables (state restore, draw callbacks, etc). I will endeavor to do that as it appears I have no other choice at this point. It is going to take time. Here is where I am at now.

    Initial load and call to server sends this:

    {"draw":1,"columns":[{"data":0,"name":"","searchable":false,"orderable":false,"search":{"value":"","regex":false}}, .......

    I click on "page 2" and nothing fires. I click on page 3 and this is sent to the server:

    draw=3&columns=[object Object]&columns=[object Object]&columns=[object Object]&columns=

    Both initial load and clicking page three produces identical results in the code using console.log to verify:

    data: function (d) {
                    console.log(d);             
                    var stringified = JSON.stringify(d);
                    console.log(stringified); 
                    return stringified;
                }
    

    So, something about initial page load and then clicking on a page button are doing something different....initial page load is a POST body which I have to extract on the server side......and the page button click is URL params.

    I using the browser developer tool > network to view what is being sent to the server.

    Alot of hair-pulling the past couple of weeks trying to implement DataTables and running well behind schedule, so frustration level is running abit high. :-)

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954
    edited April 2022

    I click on "page 2" and nothing fires

    So you don't see an XHR request in the browser's network inspector when clicking page 2?

    Maybe you can post the parameters sent using the output of the network inspector instead of the console.log.

    Are there errors in the browser's log when you click page 2?

    Sounds like you have other features, like StateRestore, that you haven't mentioned. Maybe start with a barebones Datatable config, ie, the ajax option and columns as needed, to see if that works.

    If you prefer to go with a support option contact @allan or @colin to find out the details of what is needed.

    Kevin

  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0

    Thanks, Kevin. Correct, I see no XHR request when clicking page 2. I using Edge and Chrome's Developer Tool to trace the network requests and responses. There are no javascript errors when clicking page 2.

    I am going to try removing one option at a time and test. Yes, I am doing stateLoadCallback (along with stateSave and stateSaveCallback), drawCallback, and some other custom tweaks. I will start by eliminating the state stuff and keep proceeding until it behaves correctly. If I continue to have issues with a bare bones implementation, I will reach out to the contacts you mentioned above and not clutter up the comments here until I have a solution/resolution to post.

    Again, thanks for the quick reply. It helps. :-)

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin

    Could you give me an upload trace of your table please? It might give me a clue as to what is going on. Or alternatively, a link to the page showing the issue would be even better. Drop me a PM if you don't want the link to be public.

    Allan

  • PeterDeePeterDee Posts: 7Questions: 0Answers: 0

    I discovered the problem. I was using the searchPanes option as a placeholder but with a blank configuration. It only causes issues with serverSide processing. I am not displaying the search panes using the sDom configuration, so not sure if that has any bearing on it throwing an error. Hope that helps.

    searchPanes:{}

    I missed the JS error due in part of not having my Edge developer tool output setup correctly. It was apparent in Chrome developer tool.

    Uncaught TypeError: Cannot read properties of undefined (reading '0')
    at HTMLTableElement.<anonymous> (datatables.min.js:1104:198)

    I remove the searchPanes option and it works quite well. We don't expect to implement searchPanes, so removing it. I haven't tested it with the configuration filled in...or displaying it using sDom configuration....or a combination, so not sure if the error would still occur.

    I really appreciate all of the effort in trying to resolve it on your end. Thanks! :-)

Sign In or Register to comment.