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

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received. Currently, when I press the button, both wait and scroll actions happen immediately without waiting for ...

ApEditingError: The method editAp is not defined in _this.props

I am facing an issue while trying to invoke the function editAp located in the func.js file from Edit1.js. I have provided the code snippets below for better understanding: import firebase from "firebase"; if (!firebase.apps.length) { firebase.initializ ...

Vue component encounters undefined error when passing prop array through component

My challenge is passing an array of dates to my component, but I keep encountering this error: [Vue warn]: Property or method "dates" is not defined on the instance but referenced during render I'm puzzled by this issue because I am receiving the ...

The Power Duo: jQuery Form Plugin paired with jQuery Validate

Have you ever tried using the jQuery Form Plugin in combination with the jQuery Validate plugin? The issue I'm facing is that even when the required fields are empty, the form still submits via AJAX. Check out my code snippet below: // Making the ne ...

What steps should be taken to modify an image following retrieval of data from the database?

When using the function getDataFromDb(), I am trying to retrieve the latest data from the database. Specifically, I want to use val["id"] as a condition to determine which image to display in the function GetImage. However, my attempts have not been succ ...

Is there a way to enable previous days in a UI datepicker after switching to a different month?

A different question can be found at: How can I modify the UI datepicker after switching months? In contrast to Nick Craver's solution, I encountered a separate issue: While Nick Craver sourced his dates from the js variable xml, my dates are retr ...

Parse the JSON data into a Dictionary with string keys and object values

As a beginner in C# and JSON, I recently encountered a JSON file with the following structure: {"person1":[{"name":"Bobby"},{"age":25},{"height":178},{"hobby":"piano"}],"person2":[{"name":"Tyler"},{"age":29},{"height":185}, ,{"hobby":"basketball"}],"perso ...

Issue with Bootstrap Graph not displaying when a dynamic query is applied

It's interesting that the graph works correctly with a static query, but fails to render when using a dynamic query even though the queries returned are the same. //$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP ...

Displaying Previously Selected Value in HTML Dropdown Menu

Using a combination of PHP and HTML, I have created an HTML table that is generated using a PHP while loop. The dropdown menu on the page displays all distinct portfolio names from my MySQL database by executing the following code: $query2 = "SELECT DISTI ...

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...

load google map with geocoding on an ajax-enabled page

I'm currently working on a webapp where I use AJAX to load all the pages. Recently, I faced a challenge of loading a Google map along with a page and here's how I tackled it: Great news! I managed to successfully load a Google map using just an ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Using seleniumjs to ensure that the element is ready for user input before proceeding

Currently, my application is in a state where it needs to wait for an iframe using the isElementPresent method before switching to it. The issue arises when I encounter trouble within the iFrame itself. I need to ensure that an input component within the ...

Implement a callback function in React using hooks after changing the state

Back in the days of React before hooks, setting state and calling a function after it had been set was achieved using the following syntax: this.setState({}, () => {//Callback}) Now, with hooks, what is the equivalent way to achieve this? I attempted ...

How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one. Here is my current code snippet: const input = ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...