Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on

Everything was working smoothly until I wanted to incorporate the DataTable API for adding search and sorting features to the table. The current state of my table can be viewed HERE.

It seems like there's an issue with recognizing the data being passed from the JavaScript code that I wrote, especially evident in the "Showing 0 to 0 of 0 entries" message. Is there a way to properly load data from AJAX into the DataTable script? Any assistance would be greatly appreciated! Below, you'll find a snippet of my code.

UPDATE: I moved the DataTable initialization to Inventory.js and now the DataTable occasionally works upon page load. It's quite random when trying to refresh the page multiple times. Even adding a delay before the page loads doesn't seem to have any effect. Does anyone have insights into what might be causing this?

Inventory model:

public List<Inventory> ListAll()
{
    // Code for retrieving inventory list
}

InventoryController.cs:

public JsonResult List()
{
    return Json(invDB.ListAll(), JsonRequestBehavior.AllowGet);
}

Inventory.js (Data retrieval):

function loadData() {
    // Code for loading data via AJAX
}

Index (DataTable script):

@section scripts {
    // DataTable initialization script
}

Answer №1

I am currently utilizing Jquery Datatables version 1.10 with Underscore JS for templating.

Below is the code snippet to load data from the server side:

Include the following template and table in your HTML:

<table class="table table-bordered table-condensed" id="tblAccounts"></table>

<script type="text/template" id="tmpl_Grid">
    <td><%= Id %></td>
    <td><%= Amount %></td>
    <td><%= Date %></td>
    <td><%= Type %></td>        
</script>

Then, use the following method in JavaScript to load data from the server side:

function Load() {
            var tmpl = _.template($('#tmpl_Grid').html());
            $('#tblAccounts').DataTable({
                "dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
                "paging": true,
                "info": true,
                "ordering": true,
                "search": true,
                "processing": true,
                "serverSide": true,
                "destroy": true,
                "ajax": {
                    "url": "/Accounts/LoadList",
                    "type": "POST",
                    "data": function (d) {
                        d.startDate = $("#txtStartDate").val();
                        d.endDate = $("#txtEndDate").val();
                    }
                },
                "columns": [
                    { "data": null, "title": "ID", "className": "", "orderable": false, "searchable": false },
                    { "data": null, "title": "AMOUNT", "className": "", "orderable": false, "searchable": false },
                    { "data": null, "title": "DATE", "className": "", "orderable": false, "searchable": false },
                    { "data": null, "title": "TYPE", "className": "", "orderable": false, "searchable": false }
                ],
                "order": [[0, "asc"]],
                "rowCallback": function (row, data) {
                    $(row).html(tmpl(data));
                },
                "initComplete": function (settings, json) {

                }
            });
        }

The code for the controller using EntityFramework for database processing is shown below. You can customize this as needed:

[HttpPost]
public async Task<JsonResult> LoadList(string startDate, string endDate)
{
   var search = Request.Form["search[value]"] + "";

    var totalCount = 0;
    var fList = _context.Expenses.Include(x => x.AccountType).AsQueryable();
    if (!string.IsNullOrEmpty(search))
    {
        fList = fList.Where(x => x.Description.ToLower().Trim().Contains(search.ToLower().Trim()));
    }

    var list = await fList.OrderByDescending(x => x.Id).Skip(start).Take(length).Select(x => new
    {
        x.Id,
        x.Amount,
        Date = x.Date != null ? x.Date.Value.ToString("dd-MMM-yyyy") : "",
        Type = x.AccountTypeId != null ? x.AccountType.Name : "",
        x.Description,
        x.BillAmount,
        x.Payment,
        x.AccountTypeId
    }).ToListAsync();

    if (list.Any())
    {
        totalCount = fList.Count();
    }

    var result = JObject.FromObject(new
    {
        draw,
        recordsFiltered = totalCount,
        recordsTotal = totalCount,
        data = list
    });
    return result;
}

Answer №2

Appreciate the assistance, I managed to make it work consistently by following a post on the same forum.

I made changes to my code to fetch the data like this. It turns out you need to append the data, which was crucial for making my DataTables function correctly.

$("#user tbody").append(html);

 $.ajax({
    url: "/Artwork/List",
    type: "GET",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (result) {

        $.each(result, function (key, item) {
            var html = '';
            html += '<tr>';
            html += '<td>' + item.ArtID + '</td>';
            html += '<td>' + item.Name + '</td>';
            html += '<td>' + item.Details + '</td>';
            html += '<td>' + item.Location + '</td>';
            html += '<td>' + item.Notes + '</td>';          
            html += '<td>' + dateTimeFormat(item.DateCreated) + '</td>';
            html += '<td>' + dateTimeFormat(item.LastModified) + '</td>';
            html += '<td><a href="#" onclick="return getbyID(' + item.ArtID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.ArtID + ')">Delete</a></td>';
            html += '</tr>';
            $("#user tbody").append(html);
        });
        $('#user').DataTable({
            destroy: true,              
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'print',
                    exportOptions: {
                        columns: ':visible' ,
                    }
                },
                'colvis'
            ],
            columnDefs: [{
                visible: false
            }]               
        });

Once again, thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate a button upon the user clicking the Enter key

Is there a way to automatically trigger a button click when the user presses the Enter key inside an input field? I've attempted to achieve this functionality, but have been unsuccessful so far. Here is my code snippet: <!DOCTYPE htm ...

Alter the button ID based on the currently displayed div

My mind is being driven crazy by a particular issue I am experiencing. Let me explain... I have a lengthy scrolling page with approximately 10 divs stacked one after the other without any spacing in between. Positioned at the bottom of the viewport is a bu ...

Methods for sending data from Angular to the server and vice versa

Currently, I have an application that utilizes Express along with Jade templates. I am in the process of developing a new version of the app using Angular and client-side HTML. In order to determine user permissions within my Angular code, I require acces ...

Obtaining the value of a JSON object in PHP when its key contains dots

I have a JSON data structure that looks like this: {"root":{ "version":"1", "lastAlarmID":"123", "proUser":"1", "password":"asd123##", "syncDate":"22-12-2014", ...

Utilizing jQuery for cloning elements

I need to add functionality for adding and deleting rows in multiple tables on my website. Currently, I am doing this by directly inserting HTML code using jQuery, but it has become inefficient due to the number of tables I have. I am considering creating ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

Tips for declaring a particular type during the process of destructuring in Typescript

I have my own custom types defined as shown below: export type Extensions = | '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' | '.txt' | '.jpg' | '.csv' | '. ...

Include new item in current JSON data using Java

I am facing a challenge in adding a new JSON object to "carTypes" inside the cars.json file. Can anyone guide me on how to achieve this? I can retrieve data from cars.json but do not know the process of adding data to it. The current content of my cars.j ...

Modify the CSS style of the select label and change the color of the currently selected option in MUI

For the past few days, I've been facing challenges with implementing MUI components while working on a page for a React app. I'm almost finished with my project, but there are 2 key things missing... On my page, I have utilized a Select and an ...

The functionality of HTML labels may be limited when used in conjunction with AJAX

I am using Ajax to load an HTML page and encountering a problem with the label not working properly when associated with a checkbox. Here is the data: <input type="checkbox" name="dis_net" id="dis_net" value="1" /> <label for="dis_net">Test< ...

Locate all nodes in neo4j that are connected to nodes matching a specified list of property values of a certain length

To clarify, I am interested in achieving the following (preferably using node/JS): Imagine you have a set of 3 job requirements ('JavaScript', 'PHP', 'MySQL'). In my graph setup, each Person node can be linked to multiple Sk ...

Customize jQuery Autocomplete choices depending on another jQuery Autocomplete input

I need to implement a feature where users can select a company and then an employee from that company. I came across a similar question on this link, but I specifically want both inputs to be autocomplete-enabled. This is the code snippet I currently have ...

JQuery does not allow for changing the selection of a RadioButtonFor

I am currently working on a code that determines whether or not to display contact information. To achieve this, I am using the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor. Upon loading the page, I need to switch from t ...

Tips on how to pass various checkbox values using ajax

Greetings! I am encountering an issue with sending data through ajax. Specifically, when a user selects multiple banks, only the first bank selected is retrieved in my request. I would like to receive the value of every bank selected by the user. Below is ...

Steps to run a function for updating a JSON data file

I currently have a Leaflet map displaying weather data retrieved from a Json source. There is already a function in place that updates the data every x minutes using setInterval. setTimeout(function () { refreshId = setInterval(function () { ...

The AJAX post request is coming back as null when hitting the action method

I am attempting to retrieve an array of integers by sending it via ajax post like so: function myFunction() { var items = []; for(var i = 0; i<7;i++) { items[i]= i; } SubmitForm(items); } func ...

The error message "In a Flutter application, trying to cast a 'List<dynamic>' to a 'List<int>' is not valid as they are not compatible subtypes."

Upon running the main.dart file within a Flutter app, an exception is being encountered. The code in question reads data from a data.json file and attempts to map it into a SubTypeMap class, followed by a TypeMap class. Could anyone provide insight into w ...

Is it possible for Node.js to execute individual database operations within a single function atomically?

As I delve into writing database queries that operate on node js, a puzzling thought has been lingering in my mind. There seems to be a misunderstanding causing confusion. If node is operating in a single-threaded capacity, then it follows that all functi ...

The imported JS file shows a warning that the variable 'myProperty' is defined but not utilized anywhere

When I try to import a variable from the same folder, why am I getting an error message saying it is defined but not used? I am sure that I am using it. Your input would be greatly appreciated! error 'componentName' is defined but never used. ...

Create a Vue3 Component without attaching it to the DOM

Let's consider creating a Vue3 component in the following way: import { defineComponent } from "vue"; var instance = defineComponent({ computed:{ message() { return 'Hello world' } } }) To instantiate it and ...