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