I'm trying to use the DataTables jQuery plug-in in MVC3 using an ajax request as the data source for the table.

I have a View called "Search" which contains a search form...under the form, I have the following html...

<table id="caseTable" class="clear full-width dataTable">    
    <thead>
        <tr>
            <th>Case Name</th>
            <th>Court</th>
            <th>Case Number</th>
            <th>Case Filed Date</th>
            <th>Chapter</th>
            <th>Last Researched</th>
            <th>Disposition</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

When the search form is submitted, an ajax call is sent off the get the tr elements for each record to be displayed in the table.

$.ajax({
    url: "/Home/SearchForCases",
    type: "POST",
    data: {
        CaseNumber: caseNumber,
        DebtorLastName: lastName,
        Last4SSN: last4SSN,
        FullSSN: fullSSN,
        StartDate: $("#StartDate").val(),
        EndDate: $("#EndDate").val(),
        SelectedCourtDistrictId: $("#SelectedCourtDistrictId").val(),
        SelectedChapterId: $("#SelectedChapterId").val()
    },
    success: function (result) {
        $("#caseTable > tbody").html(result);
        $("#caseTable").dataTable({
            "bDestroy": true,
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "asStripClasses": ["white-highlight"],
            "bAutoWidth": false
        });
        $("#caseTable > tbody > tr").dblclick(function () {
            $(this).removeClass("white-highlight").addClass("yellow-highlight");
        });
    },
    complete: function () {
        $("#ajaxProgress").dialog('close');
        $("#searchResults").show();
    }
});

Everything loads up fine on the first call, but on subsequent calls, the data returned from the ajax call is being appended vs replaced. I have checked the html being returned from the ajax call and it's always returning one row of data, <tr><td></td></tr> only.

share|improve this question

3 Answers

up vote 2 down vote accepted
+50

Add the bDestroy option to remove the old datatable formatting first. You could also try removing the bRetrieve option.

   success: function (result) {
        $("#caseTable > tbody").html(result);
        $("#caseTable").dataTable({
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "asStripClasses": ["white-highlight"],

            "bDestroy": true
        });

Edit

If possible, it might be better to change your code so you can use the built in datatable ajax functionality by passing in the sAjaxSource option when creating the datatable. This would require you to change your server side code to return json of data instead of html.

If that isn't possible, then you should use fnClearTable to clear the existing data before adding the new data.

var dataTable;

$.ajax({

    ...

    success: function (result) {
        // If it has been created, clear the existing data in the datatable
        if(dataTable != null) {
            dataTable.fnClearTable();
        }

        // Add your new data
        $("#caseTable > tbody").html(result);

        // Create / recreate the datatable
        dataTable = $("#caseTable").dataTable({
            "bDestroy": true,
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "asStripClasses": ["white-highlight"],
            "bAutoWidth": false
        });

        $("#caseTable > tbody > tr").dblclick(function () {
            $(this).removeClass("white-highlight").addClass("yellow-highlight");
        });
    },

    ...
});
share|improve this answer
Thanks for your response. I tried adding that option but still got the same results. – thiag0 Oct 21 '11 at 15:23
Can you try removing the bRetrieve option and see if that does anything? – kevev22 Oct 21 '11 at 15:31
I removed the bRetrieve option and I am getting different results. The datatable re-draws successfully on subsequent requests, however the rows don't stretch to the entire width of the table and subsequent calls append rows instead of replacing what is currently in the table. – thiag0 Oct 21 '11 at 16:12
any ideas on how to fix the issue with this solution? – thiag0 Oct 21 '11 at 16:50
Ensure that you have a '>' between #caseTable and tbody when getting the table element. I don't see one in your question. Also ensure that you are actually returning valid html from your ajax request. It will have to include the <tr><td>...</td>...</tr> tags since you are just replacing the html of the tbody. – kevev22 Oct 21 '11 at 17:31
show 3 more comments

Hey sorry for the poor formatting but just add this condition in your code. This will ensure that of your table already exists and you are just going from one page to another then your data will be replaced and not appended. Hope this helps

if(typeof datataTable !="undefined" && datatable != null)
{ 
    $.ajax({

    success: function (result) {
    // If it has been created, clear the existing data in the datatable
    if(dataTable != null) {
        dataTable.fnClearTable();
    }

    // Add your new data
    $("#caseTable > tbody").html(result);

    // Create / recreate the datatable
    dataTable = $("#caseTable").dataTable({
        "bDestroy": true,
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "asStripClasses": ["white-highlight"],
        "bAutoWidth": false
    });

    $("#caseTable > tbody > tr").dblclick(function () {
        $(this).removeClass("white-highlight").addClass("yellow-highlight");
    });
},


});} else{dataTable.fnClearTable(0);dataTable.fnDraw();}
share|improve this answer

try initializing your datatable outside of the success callback and then just call the fnDraw() function to redraw the table after you have updated the html of the table.

EDIT

var dataTable = $("#caseTable").dataTable({
            "bJQueryUI": true,
            "bRetrieve": true,
            "bServerSide": true,
            "sAjaxSource": //Url to hit to query your database and return table data
            "sPaginationType": "full_numbers",
            "asStripClasses": ["white-highlight"]
        });

$("#caseTable tbody tr").dblclick(function () {
            $(this).removeClass("white-highlight").addClass("yellow-highlight");
        });

$.ajax({
    url: "/Home/SearchForCases",
    type: "POST",
    data: {
        CaseNumber: caseNumber,
        DebtorLastName: lastName,
        Last4SSN: last4SSN,
        FullSSN: fullSSN,
        StartDate: $("#StartDate").val(),
        EndDate: $("#EndDate").val(),
        SelectedCourtDistrictId: $("#SelectedCourtDistrictId").val(),
        SelectedChapterId: $("#SelectedChapterId").val()
    },
    success: function () {
        dataTable.fnDraw();
    },
    complete: function () {
        $("#ajaxProgress").dialog('close');
        $("#searchResults").show();
    }
});
share|improve this answer
@Kevin - Thanks for the response. I tried moving the initialization to the top of the script file and then calling the fnDraw() function after updating the html but it clears out the table. I also tried calling it before re-loading the html and I get the data but no styling. – thiag0 Oct 21 '11 at 15:23
can you instead refactor your code to use serversideprocessing? – Keith.Abramo Oct 21 '11 at 15:24

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.