Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fnServerData?

Can anyone show me how to use fnServerData?.

$(document).ready( function() {
  $('#example').dataTable( {
    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "xhr.php",
    "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
      oSettings.jqXHR = $.ajax( {
        "dataType": 'json',
        "type": "POST",
        "url": sSource,
        "data": aoData,
        "success": fnCallback
      } );
    }
  } );
} );

Below is my Ajax call, i want to replace the ajax call with the fnServerData.

   $.ajax({
        type: 'GET',
        url: url,
        jsonp: true,
        contentType: "application/json",
        dataType: 'jsonp',
        success: function (data) {
            $.each(data.value, function(i,item){
                table.fnAddData(item);
            });
        },
        error: function (e) {
            console.log(e.message);
        }
    });

http://datatables.net/ref#fnServerData

What is sSource, fnCallback and oSettings?. Can anyone show me how to use fnServerData?.

like image 650
Shane Avatar asked Feb 28 '14 21:02

Shane


1 Answers

sSource, fnCallback and oSettings are generated by Datatables.

sSource is the url for your ajax call. When you initialize the datatable you specify this in sAjaxSource. So you should pass in your url var as sAjaxSource.

oSettings is created and maintained by datatables js. It stores important information about the state of your datatable. Detailed documentation available here: https://datatables.net/docs/DataTables/1.9.0/DataTable.models.oSettings.html

I think however, your success function is unnecessary. You should specify aoColumns as an option during initialization and then datatables will populate the data for you.

$(document).ready( function() {
 $('#example').dataTable( {
   "aoColumns": [
       { "mData": "engine" },
       { "mData": "browser" },
       { "mData": "platform.inner" },
       { "mData": "platform.details.0" },
       { "mData": "platform.details.1" }
     ]
   }),
   "bProcessing": true,
   "bServerSide": true,
   "sAjaxSource": url,
   "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
     oSettings.jqXHR = $.ajax( {
       "dataType": 'json',
       "type": "POST",
       "url": sSource,
       "data": aoData,
       "success": fnCallback,
       "error": function (e) {
           console.log(e.message);
       }
     });
   }
 });
});

More information on aoColumns here: http://www.datatables.net/usage/columns Also, have a looka the examples on the datatables page. There should be an example for anything you need: http://www.datatables.net/usage/columns

Regards, Saz


like image 198
SazD Avatar answered Nov 09 '22 01:11

SazD