title: How create datatables dynamically on button click
body: <p>I want to create jquery Datatables onclick of button a function will be called and inside function ajax will get data from database. I am passing certain data to server on click via url parameter.</p>
  
  <p>Below is my ajax call on button click.</p>
  
  <pre><code>$(document).ready(function() {
  $('#example').DataTable();
  </code></pre>
  
  <p>}   </p>
  
  <pre><code>function loadData() {
  
  var strUrl = "batch.jsp?patientname=" + patientname
  + "&amp;dobstart=" + dobstart + "&amp;dobend=" + dobend
  + "&amp;startage=" + startage + "&amp;endage=" + endage
  + "&amp;location=" + location + "&amp;account="
  + account;
  
  
  $.ajax({
  url : strUrl,
  type : "POST",
  dataType: 'json',
  success : function(data) {
      formdata += "&lt;table id='patientdata' class='display' cellspacing='0' width='100%'&gt;"
                                          +"&lt;thead&gt;"
                      +"&lt;tr&gt;"
                      +"&lt;th&gt;ID&lt;/th&gt;"
                      +"&lt;th&gt;Name&lt;/th&gt;"
                      +"&lt;th&gt;Date of Birth&lt;/th&gt;"
                      +"&lt;th&gt;Location&lt;/th&gt;"
                      +"&lt;th&gt;Email Address&lt;/th&gt;"
                      +"&lt;/tr&gt;"
                      +"&lt;/thead&gt;"
                      +"&lt;tbody&gt;";
  
  $.each(data.patientdata, function(index, item) {
      formdata += "&lt;tr&gt;"
              +"&lt;td&gt;"+item.uid+"&lt;/td&gt;"
              +"&lt;td&gt;"+item.name+"&lt;/td&gt;"
              +"&lt;td&gt;"+item.dob+"&lt;/td&gt;"
              +"&lt;td&gt;"+item.location+"&lt;/td&gt;"
              +"&lt;td&gt;"+item.email+"&lt;/td&gt;"
              +"&lt;/tr&gt;";
  
    });                   
  
  formdata += "&lt;/tbody&gt;&lt;/table&gt;";
  $("#ptdata").html(formdata); // div in html
  $('#exampledata').dataTable(); 
  
  },
  error : function(thrownError) {
      alert("Error in ajax post call "+thrownError);
  }
  </code></pre>
  
  <p>});
  }</p>
  
  <p>I found one code but here server is called on load in document ready but I want to call it during onclick of button.</p>
  
  <p>Below code which makes a call to server on load</p>
  
  <pre><code>// POST data to server
  $(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
    } );
  }
  } );
  } );
  </code></pre>