0

I don't want to populate the data table when it loads. I would like instead to return json data from an ajax call and bind that to the datatable. How is this possible?

$(function () {
var ajaxFormSubmit = function () {
    var $form = $(this);

    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
    };

    $.ajax(options).done(function (data) {
        var $target = $($form.attr("data-search-target")); //resultsTable
        var $newHtml = $(data);

        $target.data = data; //QUESTION: How to update the datatable source here?

        var $target = $($form.attr("data-photo-target")); 


        //ANSWER
        $target.dataTable().fnClearTable();
        $target.dataTable().fnAddData(data);
    });

    return false;
};

$("form[data-search-ajax='true']").submit(ajaxFormSubmit);

$('#resultsTable').DataTable({
    "ajax": {
        "data": ""
    },
    "columns": [
        { "data": "Name", "autoWidth": true },
        { "data": "Date", "autoWidth": true },
        { "data": "File", "autoWidth": true },
        { "data": "Path", "autoWidth": true }
    ]
});
});

My controller is functioning as expected and is returning the json data

[HttpGet]
public ActionResult Search(SearchData searchData)
{
    var searchViewModel = new SearchViewModel 
{
    SearchResults = _contentProvider.GetData(searchCriteria)
};

....

if (Request.IsAjaxRequest())
{
    return Json(searchViewModel.SearchResults, 
        JsonRequestBehavior.AllowGet);
    }
}
....

UPDATE: I've edited original and used approach recommended in the comment below. See the 2 lines added below //ANSWER

user48408
  • 3,234
  • 11
  • 39
  • 59
  • [How to manually update datatables table with new JSON data](https://stackoverflow.com/questions/27778389/how-to-manually-update-datatables-table-with-new-json-data) –  Aug 09 '17 at 10:17
  • Thanks. I used the second approach recommend. Will update – user48408 Aug 09 '17 at 11:38

0 Answers0