Solved

Reloading a Data Table

Posted on 2016-09-03
10
84 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 52

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 52

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
 

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 52

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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 52

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article describes how to create custom column layout styles for Bootstrap. The article uses 5 columns to illustrate the concept, but the principle can be extended to any number of columns.
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…

911 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now