Solved

Reloading a Data Table

Posted on 2016-09-03
10
73 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
Comment Utility
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 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
Comment Utility
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 51

Expert Comment

by:Julian Hansen
Comment Utility
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
Comment Utility
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 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:Crystal Rouse
Comment Utility
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 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
Yes!  Thank you for the help! I'm going to try this today.
0
 

Author Closing Comment

by:Crystal Rouse
Comment Utility
Thanks for all the help!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
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…

763 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

10 Experts available now in Live!

Get 1:1 Help Now