Solved

Reloading a Data Table

Posted on 2016-09-03
10
121 Views
Last Modified: 2016-09-08
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
Comment
Question by:Crystal Rouse
10 Comments
 

Author Comment

by:Crystal Rouse
ID: 41782928
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
 
LVL 54

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41783010
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
 
LVL 54

Expert Comment

by:Julian Hansen
ID: 41783012
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
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 

Author Comment

by:Crystal Rouse
ID: 41783240
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
 
LVL 54

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41783390
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
 

Author Comment

by:Crystal Rouse
ID: 41783654
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
 
LVL 54

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41783665
Have you tried using the AJAX function of DataTables
https://datatables.net/examples/data_sources/ajax.html
0
 
LVL 19

Accepted Solution

by:
Manoj Patil earned 250 total points
ID: 41787345
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
 

Expert Comment

by:Crystal R
ID: 41787851
Yes!  Thank you for the help! I'm going to try this today.
0
 

Author Closing Comment

by:Crystal Rouse
ID: 41789383
Thanks for all the help!
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question