[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 762
  • Last Modified:

Reloading a Data Table

I have a data table that is populated on page load with links to open a modal. When the modal is filled out and the user clicks Submit, I have a function that works.  On success, I need to open a confirmation modal, this works.  And then I need to reload the data table.  This is the part I'm stuck on.  I've tried several possible ways, the div that I am requesting to reload contains no data and I receive an error for the data table that is does not contain any data.  

Can someone send an example of where they have done something similar as far as reloading a datatable?  Thank You!
0
Crystal Rouse
Asked:
Crystal Rouse
4 Solutions
 
Crystal RouseWeb Developer/Database AdminAuthor Commented:
Here is some of my code:

Data Table:

function pageReady() {

var table = $('<table class="table table-hover table-striped row-border order-column">');

    table.prependTo('#MyTable');

    var myTable =  table.DataTable({
        data: myData,

        columns: [
            {
                targets: [0],
                title: "Ticket #", data: "TicketID", render: function (data) {
                    if (isAdmin) {
                        return '<u class="myLink" data-toggle="modal" data-target="#UpdateTicket">' + data + '</u>';
                    }
                    else {
                        return '<u class="myLink" data-toggle="modal" data-target="#TicketDetail">' + data + '</u>';
                    }
                }
            },
            { title: "Title", data: "Title", "width": "20%" },
            { title: "Description", data: "Description", "width": "25%" },
            { title: "Submitted By", data: "SubmittedUserName", class: "centered-text" },
            { title: "Submitted On", data: "SubmitDate", defaultContent: '', render: RenderShortDate, class: "centered-text" },
            { title: "Category", data: "CategoryName", class: "centered-text" },
            { title: "Status", data: "StatusName", class: "centered-text" }

        ],
        deferRender: true

    });

I populate the modal like this:

$('table').on('click', '.myLink', function () {

        var dt = $(this).closest('table').DataTable();
        var row = dt.row($(this).closest('tr')[0]);
        var ticket = row.data();

        if (false) {

            var data = $(this).text();

        }


        //populate the ticket detail modal
        $("#UpdateTicket h3").text("Ticket ID: " + ticket.TicketID);
        $('#Name').val(ticket.SubmittedUserName);
        .....and so forth
  });

This is the click event for the Update button on the modal:
$('#update').click(function () {

        updateform();
    });

This is the Update Form Function:
function updateform() {

    Validation code here....


        var newResolution = {
            Fields here....
            TicketStatusID: $("#Status1").val()
        };

        $.ajax({
            type: "POST",
            url: "ViewTickets.aspx/myMethod",  //this works
            data: JSON.stringify(myMethod),
           
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        })
        .done(function (msg) {
            $('#UpdateTicket').modal('hide');
           
           $('#UpdateTicketConfirmation').modal('show');
            reloadtickettable();  //this does not work
         
        })
        .error(function (jqXHR, status, error) {
            alert('OOPS! Something went wrong: ' + status + ' : ' + error);
        })
    }
};

This is the function that does not work:
function reloadtickettable() {
   
 //   $('#MyTable').load(document.URL + ' #MyTable');
    myTable.fnDraw();
 
};






}
0
 
Julian HansenCommented:
Your reloadtitckettable function calls back to the server to get the data for the table - correct?

This is an async operation so any instructions immedatialy after the load are going to fire before the load is finished. So if myTable.fnDraw(); needs to fire after the data has been returned from the server then you are going to have to put that in the load call back.

Example
$('#MyTable').load(document.URL + ' #MyTable', function() {
   myTable.fnDraw();
});

Open in new window

0
 
Julian HansenCommented:
I am not really on top of your refresh mechanism - can you elaborate on what you are doing there to refresh the data table. Are you asking the server to send you a fresh copy?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
Crystal RouseWeb Developer/Database AdminAuthor Commented:
Thanks for the response!  I need to refresh the data.  How do I ask the server to send me a fresh copy of the data?  I use a method in the .cs file to obtain a serialized list from the database.
0
 
Julian HansenCommented:
You can do it with a .load(), .post(), .get() or .ajax call (assuming you are wanting to do it via AJAX).

Your server side process sends back the data which you then insert into the data table. I am confused because it appears you are already doing that (or trying to). Is the question about how to do this or is it about why one part of it is not working properly?
0
 
Crystal RouseWeb Developer/Database AdminAuthor Commented:
When the page loads, my data table works.  What doesn't work is when I try to refresh the page. The datatable is empty.

When I call function reloadtickettable(), the datatable is empty.

Thank you for your help!
0
 
Julian HansenCommented:
Have you tried using the AJAX function of DataTables
https://datatables.net/examples/data_sources/ajax.html
0
 
Manoj PatilSr. Software EngineerCommented:
Is this what you want ?

http://stackoverflow.com/questions/11797719/refresh-datatable-on-ajax-success


function dialogForms() {
  $('a.menubutton').click(function() {
    var id = this.id;// Save the id of the clicked button
    var a = $(this);
    $.get(a.attr('href'),function(resp){
      var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
      $('body').append(dialog);
      dialog.find(':submit').hide();
      dialog.dialog({
        title: a.attr('title') ? a.attr('title') : '',
        modal: true,
        buttons: {
          'Save': function() {
                submitFormWithAjax($(this).find('form'), id);// Pass the id to the function 

function submitFormWithAjax(form, id) {
  form = $(form);
  var table_id;
  // Choose the table to display depending on the id, i made some guesses but adjust this
  switch(id){
    case 'view_academic': table_id = '#academic_table';
    break;
    case 'view_business': table_id = '#business_table';
    break;
    case 'line_managers': table_id = '#line_managers_list';
    break;
  }
  $.ajax({
    url: form.attr('action'),
    data: form.serialize(),
    type: (form.attr('method')),
    dataType: 'script',
    success: function(data){
        $(this).dialog('close');
        // Refresh table
        var oTableToUpdate =  $(table_id).dataTable( { bRetrieve : true } );
        $oTableToUpdate .fnDraw();
        // Hide all tables
        $('table').hide();
        // Show the refreshed
        $(table_id).show();

   }
  });
  return false;
}

Open in new window


To update a table simply call fnDraw() on it. Since you are not using global variables, you must retrieve the table first

var $lmTable = $("#line_managers_table").dataTable( { bRetrieve : true } );
$lmTable.fnDraw();

Open in new window

0
 
Crystal RCommented:
Yes!  Thank you for the help! I'm going to try this today.
0
 
Crystal RouseWeb Developer/Database AdminAuthor Commented:
Thanks for all the help!
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now