Search code examples
jqueryajaxdatatables

How do you dynamically set ajax data in DataTables?


I'm using DataTables 1.10.15 and have read about how you can specify the data attribute in an ajax call like so:

$(document).ready(function() {
    var MyTable = $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "scripts/server_processing.php",
            "data": function ( d ) {
                d.myKey = "myValue";
                // d.custom = $('#myInput').val();
                // etc
            }
        }
    } );
} );

However, this example just has hardcoded values (or form input values like $('#myInput').val()).

I have an application where I need to be able to pass in various different objects of data and then have the ajax call run.

I can't see how this is possible and have looked at the following https://datatables.net/examples/server_side/custom_vars.html.

The reason I want to do this is because I'm building an application with several different forms. I need to choose which form to send as the data! When the users enter terms in a particular form, I want to pass that forms data to my ajax script and then have DataTables redraw the table (which I can do using the .draw() method):

MyTable.draw();

However, I don't understand how I can dynamically specify what goes in data:. I could do something like this in the ajax call:

"ajax": { 
        "url" : "scripts/server_processing.php",
        "data" : function ( d ) {
            d.primarySearch = $('#form1').serialize(),
            d.secondSearch = $('#form2').serialize(),
            d.thirdSearch = $('#form3').serialize(),
        }
    }

But, if the data I'm doing the search on is in #form1, I just want to pass that data, and not the data from #form2 and #form3. But since that varies each time, I need to be able say which form(s) to pass in to the data: object.


Solution

  • I am also using the server side processing. you can call it as per below code:

    This is for static form id

      ajax: {
                "url": 'api/v1/datatable/' + method,
                "type": "POST",
                "data": jQuery('#frmid').serialize(),
            },
    

    This is for dynamic form id

    var form_id = 'form1' ;
    
    $(document).ready(function() {
        var MyTable = $('#example').DataTable( {
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "scripts/server_processing.php",
                "data": jQuery('#' + form_id).serialize(),
            }
        } );
    } );
    
    $(document).on('keyup','.search_text',function(){
    
        form_id = $(this).closest('form').attr('id');
        MyTable.draw(); 
    })
    

    Hope this will helpful to you.