Use ajax-sourced data with client-side processing?

Use ajax-sourced data with client-side processing?

cojlcojl Posts: 14Questions: 3Answers: 1

Hey guys, I'm pretty new to DataTables but loving it so far!

I'm currently processing filtering and paging on the server, with a JSON-object as data-source which is retrieved directly from my server with ajax.

What I want to do now is to keep the "data" server-side, but handle the processing(filter, paging etc) on the clientside. The reason for this is that my database won't be huge, and it would probably be better to keep the processing client-side?

My table initialization looks as follows:

 $(document).ready(function () {
           table = $('#myTable').DataTable({
            "responsive": true,
            "serverSide": true,
            "ajax": {
                "type": "POST",
                "url": '/Table/DataHandler',
                "contentType": 'application/json; charset=utf-8',
                'data': function (data) { return data = JSON.stringify(data); }
            },
            "drawCallback": function (settings) {
                $('.card').hide();
                console.log(table.rows().data());
            },
            "stateSave": true,
            "paging": true,
            "cache": false,
            "deferRender": true,
            "columns": [
            { "data": "Id" },
            { "data": "Name" },
            {
                "data": "Date",
                "render": function (data, type, row) {
                     return (moment(data).format("YYYY-MM-DD"));
                     }
            }],
            "order": [0, "asc"],
        });
    });

This works beautifully, but when I try to change the serverside variable to false along with the ajaxcall, I can't get it to work.

Any input is greatly appreciated! Thanks :)

This question has an accepted answers - jump to answer

Answers

  • cojlcojl Posts: 14Questions: 3Answers: 1

    Basically, if I just swap from serverside: true to false, the table doesn't load any data even though my ajaxrequest and datahandler remains the same. Am I missing something essential?

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    Answer ✓

    Well the serverSide works by sending data to the specified target URL, such as length, filter, rows, etc etc..

    The ajax works simply by sending a GET request to the URL specified, and then caching the data.

    So basically, you're trying to tell DataTables to send a POST request to something its not expecting to send parameters to, thats not how it should work.

    What I want to do now is to keep the "data" server-side, but handle the processing(filter, paging etc) on the clientside. The reason for this is that my database won't be huge, and it would probably be better to keep the processing client-side?

    So then the ajax option is perfect for you. You just need to take out all the "processing" functionality from the server side, and have it output just a JSON string.

    So change this:

    "ajax": {
        "type": "POST",
            "url": '/Table/DataHandler',
            "contentType": 'application/json; charset=utf-8',
            'data': function (data) { return data = JSON.stringify(data); }
    }
    

    To just:

    "ajax": "//website.com/file_that_returns_JUST_a_JSON_string.php"
    

    If you take a look at the AJAX Source example, and look at the AJAX tab, youll see an example of what it needs to return..

    {
      "data": [
        [
          "Tiger Nixon",
          "System Architect",
          "Edinburgh",
          "5421",
          "2011/04/25",
          "$320,800"
        ],
        [
          "Garrett Winters",
          "Accountant",
          "Tokyo",
          "8422",
          "2011/07/25",
          "$170,750"
        ],
        [
          "Ashton Cox",
          "Junior Technical Author",
          "San Francisco",
          "1562",
          "2009/01/12",
          "$86,000"
        ]
        /* Etc.... */
      ]
    }
    
  • cojlcojl Posts: 14Questions: 3Answers: 1

    Thank you for your response. I think I'm almost there now. I serialize the objectarray on the serverside before returning it in the ajax request now. What I get is a JSON string with all the objects listed, but I miss the "data" tag used in all the examples. I get an ajax error upon load, maybe caused by this?

    Basically my string looks like:

    {
        [
          "Tiger Nixon",
          "System Architect",
          "Edinburgh",
          "5421",
          "2011/04/25",
          "$320,800"
        ],
        [
          "Garrett Winters",
          "Accountant",
          "Tokyo",
          "8422",
          "2011/07/25",
          "$170,750"
        ],
        [
          "Ashton Cox",
          "Junior Technical Author",
          "San Francisco",
          "1562",
          "2009/01/12",
          "$86,000"
        ]
    }
    

    Thanks again!

  • cojlcojl Posts: 14Questions: 3Answers: 1
    edited October 2015

    I just noticed it has something to do with my serverside code (most likely), since it returns a 500 error when I debug in devtools. I'll go through my code and get back later!

    Thanks again for your time, still pretty new to both ajax and datatables :)

  • VitalizVitaliz Posts: 71Questions: 7Answers: 1
    edited October 2015

    Hi, cojl.
    If you just load full package of DataTables 1.10.9, you can see a lot of working demo code in
    /home/datatables/examples directory. It contain server-side scripts too.
    I solved main part of my questions, when looked at this catalog carefully.

    Regards.

  • cojlcojl Posts: 14Questions: 3Answers: 1

    Thanks for your response! I've been going through the examples but I can't seem to solve this specific issue with them. I've made progress with the ajax request, but now I get "Requested unknown parameter "Id" for row "0".

     $(document).ready(function () {
            table = $('#myTable').DataTable({
                "responsive": true,
                "serverSide": false,
                "dom": '<"pull-left"f><"pull-right"l><"center"p>',
                "ajax": '/Table/DataHandler',
                "drawCallback": function (settings) {
                    $('.card').hide();
                },
                "stateSave": true,
                "paging": true,
                "cache": false,
                "deferRender": true,
                "columns": [
                { "data": "Id" },
                {
                    "data": "Date",
                    "render": function (data, type, row) {
                        return (moment(data).format("YYYY-MM-DD"));
                    }
                },
    
    public JsonResult DataHandler()
            {
                 user_Result[] arr = new user_Result[] { };
    
                 using (DbContext dc = new DbContext())
                 {
                    arr = dc.spRegistrations().ToArray();
                 }
                 var json = new JavaScriptSerializer().Serialize(arr);
                 return Json(new { data = json }, JsonRequestBehavior.AllowGet);
    

    Thanks again!

  • VitalizVitaliz Posts: 71Questions: 7Answers: 1

    I can't say nothing without seen your php script. Do you describe RowId setup in it?
    Look here https://www.datatables.net/examples/server_side/ids.html

  • cojlcojl Posts: 14Questions: 3Answers: 1

    No, I'm not using RowId's atm. The second codesnippet in my last reply is from my serverside code, written in ASP.net MVC (C#). It gets called, and properly returns a JSON string with valid format, which is why I'm confused as to why I can't get anything to load clientside.

    Thanks again!

  • VitalizVitaliz Posts: 71Questions: 7Answers: 1

    Sorry, I can`t help you with ASP.net MVC.

  • cojlcojl Posts: 14Questions: 3Answers: 1

    I understand, thanks anyways

  • triestries Posts: 4Questions: 2Answers: 0

    cojl,

    We're you ever able to find a resolution? I'm having the same issue and cannot figure it out. The data is returned but nothing rendered in the table.

    The paging info reads: Showing 0 to 0 of 0 entries (filtered from 74 total entries)

    Thanks.

  • ShruShru Posts: 1Questions: 0Answers: 0

    Hi cojl, I am facing the same error Showing 0 to 0 of 0 entries.
    were you able to figure out?

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin

    @tries: It sounds like you aren't returning the recordsTotal and recordFiltered parameters correctly for server-side processing

    @Shru: Please link to a test case showing the issue, per the forum rules.

    Allan

This discussion has been closed.