Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Datatables populate after form post

I'm trying to do a form submit (POST) with some parameters and based on the parameters I want to populate my datatable. But I'm not very good with Javascript (My language is Java), so I'm trying to do it with an Ajax call. But it won't work for me. Everything works for me, except doing a POST with parameters to the servlet. The datatable always populate automatically, but it should populate after the form submit.

Does someone know an example of my case? I read a lot of form posts here and tutorials, but none of this case (?).

My code is now as follows, this works for me. Except I can't sort or search anymore in this table. What is missing?

Thank you.

<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>

<form name="myform" id="myform" action="" method="POST">  
  <label for="season">Season:</label>  
  <input type="text" name="season" id="season" value=""/> <br />
  <label for="type">Type:</label>  
  <input type="text" name="type" id="type" value=""/> <br/>
  <input type="button" id="btnSubmit" name="btnSubmit" value="Search"> 
</form>

<table class="display" id="example">
  <thead>
    <tr>
      <th>Name</th>
      <th>NationId</th>
      <th>RegionId</th>
      <th>Attendance</th>
    </tr>
  </thead>
  <tbody>
    <!-- data goes here -->
  </tbody>
</table>

<script>
  $("#btnSubmit").click( function() {
    var formData = "season=" + $("input#season").val() + "&type=" + $("input#type").val();
    $('#example').dataTable( {
      "bJQueryUI": true,
      "bProcessing": true,
      "bDestroy": true,
      "sAjaxSource": "/servlets/service/competitions/",
      "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
        oSettings.jqXHR = ${esc.d}.ajax( {
          "dataType": 'json',
          "type": "POST",
          "url": sSource,
          "data": formData,
          "success": fnCallback
          } );
      }
    } );
  } );
</script>
like image 822
Danny Gloudemans Avatar asked Dec 16 '22 12:12

Danny Gloudemans


1 Answers

Ok, this is the full answer for you question

You need to make three events, the first load the database information in your datatable, the second event inserts the new information on the database, and the third refresh the datatable content.

<html>
<head>
<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
//Global variables 
var otable;
var dataTab;
$(document).ready(function () {
    chargeData();
    $('#btnSubmit').click(function () {
       insertData();
    });   
}); 

// 1. charge all data 
function chargeData() {
    $.ajax({
        type: "POST",
        //create a method for search the data and show in datatable
        url: "/servlets/service/competitions/",
        contentType: "application/json; charset=utf-8",
        data: '{ }',
        dataType: "json",
        success: AjaxGetFieldDataSucceeded,
        error: AjaxGetFieldDataFailed
    });
}

function AjaxGetFieldDataSucceeded(result) {
    if (result != "[]") {

        dataTab = $.parseJSON(result);
        //instance of datatable
        oTable = $('#example').dataTable({
            "bProcessing": true,
            "aaData": dataTab,
            //important  -- headers of the json
            "aoColumns": [{ "mDataProp": "season" }, { "mDataProp": "type" }],
            "sPaginationType": "full_numbers",
            "aaSorting": [[0, "asc"]],
            "bJQueryUI": true,

        });

    }
}

function AjaxGetFieldDataFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

// 2. this function only insert the data in your database
function insertData() {
    var email = $("#season").val();
    var evento = $("#type").val();
    $.ajax({
        type: "POST",
        //in this method insert the data in your database
        url: "/servlets/service/competitions/",
        contentType: "application/json; charset=utf-8",
        data: '{ season : "' + season + '", type : "' + type + '"}',
        dataType: "json",
        success: AjaxUpdateDataSucceeded,
        error: AjaxUpdateDataFailed
    });
}

function AjaxUpdateDataSucceeded(result) {
    if (result != "[]") {
        alert("update ok");
        refreshDatatable();
    }
}

function AjaxUpdateDataFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

// 3. This function refresh only the datatable not all page  in varius events you can call like INSERT,UPDATE,DELETE ;D
function refreshDatatable() {
    $.ajax({
        type: "POST",
        //same event used in chargeData function
        url: "/servlets/service/competitions/",
        contentType: "application/json; charset=utf-8",
        data: '{ }',
        dataType: "json",
        success: AjaxRefreshDataSucceeded,
        error: AjaxRefreshDataFailed
    });
}

function AjaxRefreshDataSucceeded(result) {
    if (result.d != "[]") {
        var jposts = result;
        dataTab = $.parseJSON(jposts);
        //when the instance of datatable exists, only pass the data :D
        oTable.fnClearTable();
        oTable.fnAddData(dataTab);
    }
}

function AjaxRefreshDataFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

<script>
</head>
<body>
<form name="myform" id="myform" action="">  
  <label for="season">Season:</label>  
  <input type="text" name="season" id="season" value=""/> <br />
  <label for="type">Type:</label>  
  <input type="text" name="type" id="type" value=""/> <br/>
  <input type="button" id="btnSubmit" name="btnSubmit" value="Search"> 
</form>

<table class="display" id="example">
  <thead>
    <tr>
      <th>SEASON</th>
      <th>TYPE</th>
    </tr>
  </thead>
  <tbody>
    <!-- data goes here -->
  </tbody>
</table>
</body>
</html>
like image 181
William Ballesteros Avatar answered Dec 26 '22 17:12

William Ballesteros