Refreshing the DataTable with new data using DataTable.ajax.reload does not appear to be effective

Feeling like I'm hitting my head against a brick wall right now. I have a Datatable that is supposed to be populated by a GET call to an API based on the selection from a dropdown box. The goal is for the user to choose an option from the dropdown and then see the table reload with data fetched from the call. Although the API is being called and data is being returned with each selection, the table is not displaying the data or refreshing as expected.

Check-In Page

@model IEnumerable<Vidly.Models.Customer>
@{
    ViewBag.Title = "CheckIn";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Check In</h2>

<div class="form-group">
    @Html.DropDownList("Customers", 
    new SelectList(Model, "Id", "Name"), "Please select a customer", 
    new { @class = "form-control", @id = "customers"})
</div>

<table id="rentals" class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>Customer ID</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

@section scripts
{
    <script>
        $(document).ready(function () {
            var customerId;
            var table = $("#rentals").DataTable({
                ajax: {
                    type: 'GET',
                    url: '/api/RentalsApi/',
                    data: function (d) {
                        d.id = customerId ? customerId : -1;
                    },
                    dataSrc: ""
                },
                columns: [
                    {
                        data: "name"
                    }
                ]
            });

            $('#customers').on('change', function (e) {
                console.log(this.value);
                customerId = this.value;
                table.ajax.reload();
            });
        });
    </script>
}

Rentals API

// GET /api/RentalsApi/{1}
[HttpGet]
public IHttpActionResult GetRental(int id)
{
    if (id == -1) return Json(new System.Web.Mvc.EmptyResult());

    var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
    return Ok(customer);
}

Customer Model

using System;
using System.ComponentModel.DataAnnotations;

namespace Vidly.Models
{
    public class Customer
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "Please enter customer's name.")]
        [StringLength(255)]
        public string Name { get; set; }

        public bool IsSubscribedToNewsletter { get; set; }

        public MembershipType MembershipType { get; set; }

        [Display(Name = "Membership Type")]
        public byte MembershipTypeId { get; set; }

        [Display(Name = "Date of Birth")]
        [Min18YearsIfAMember]
        public DateTime? Birthdate { get; set; }
    }
}

Answer №1

To update the table after making an ajax api call, follow these steps:

var dataTable = $("#rentals").DataTable();
dataTable.clear().rows.add(newData).draw(); // where newData is the data fetched from the ajax call

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

What's the most effective method for transferring data to different components?

How can I efficiently pass a user info object to all low-level components, even if they are grandchildren? Would using @input work or is there another method to achieve this? Here is the code for my root component: constructor(private _state: GlobalSta ...

Using AJAX to dynamically update text areas on a webpage without the need to refresh the

My goal is to dynamically update the content of a textarea on my webpage when a form is submitted, without having to refresh the entire page. Initially, I attempted to achieve this using AJAX with the following code: $("#db_info").load(document.location.h ...

Mutual benefit in Parent and Child interaction

I am facing a situation where I have two components: Parent and Child. Here is the scenario: The Child component receives values from the Parent, which are constantly changing The Child component always reflects the updated value The Child component man ...

Tips on extracting JSON subcategories?

I am currently attempting to retrieve information from a local JSON file using the following JavaScript script: let accordion=document.querySelector('#accordion'); fetch('countries.json') .then(function(response){ return response.js ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Is there a way for me to ensure that a response is only returned once a method call has been completed in

Seeking assistance with a Node.js application using Express. I am trying to create a REST endpoint that returns the response of an HTTP call. However, no matter what I attempt, it always returns before the HTTP request has completed. Can anyone provide g ...

Fixing Laravel 5.2 and jQuery validation issue: Accessing a property from a Non-Object

Currently, I am utilizing the jQuery validation plugin to check whether a username already exists or not. The documentation regarding the validation plugin states: The server-side resource is accessed through jQuery.ajax (XMLHttpRequest) and receives k ...

Find similarities and differences between two CSV files

Dealing with 2 large files, both exceeding 1 million rows: The first file contains only an md5 hash The second file contains pairs of md5 and email addresses My task is to compare these two files and if the md5 hashes match, write the corresponding emai ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

The protocol at msa port 587 is unidentified with SSL23_GET_SERVER_HELLO

For sending email notifications when a new user registers or forgets their password, I am currently working on a Linux environment with an app built using node.js. Error: [Error: 140020013401920:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown ...

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

What can I do to enhance the performance of my password?

Exploring React for the first time and currently working on a registration page, I've run into a performance glitch with my password validation function. Check out the code below: State Declarations const [errorDiv, setErrorDiv] = useState(0); ...

Checking if a phone number begins with a zero using a regular expression

Is there a way to ensure that numbers entered into a field always start with a 0? Initially, I thought the company wanted to mandate entering 0 first, but I believe there might be a more elegant solution. function validateNumber(dataValues, setErrors) ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...

Node.js woes: troubleshooting object output issues

I am currently delving into the world of Node.js and express as I explore building a simple bike configuration. I have created an object that encompasses all the necessary properties for this project. After exporting this object, I attempted to display it ...

Is it necessary to retrieve the file using AJAX or should I use a different

When I have a file stored on the server that I need to parse using JavaScript, do I need to use AJAX to call JavaScript to parse the document and return the results, or can I retrieve the file directly with JavaScript without AJAX? The results will be dis ...

utilizing services across multiple controller files

Service - optionService.js controllers - app.js & welcomeCtrl.js & otherCtrl.js app.js var app = angular.module('mainapp', ['mainapp.welcome','optionServiceModule']); app.controller('mainappCtrl', functio ...

Unique name for the transition animation on SSR-Nuxt page transitions

Attempting to implement a dynamic transition name for Nuxt page transitions as shown below: export default{ data() { return { prevHeight: 0, transitionName: 'page' }; }, transition: { na ...

Connecting to a specific section of a webpage

I'm facing an issue with my menu links on a webpage where they are not directing to the intended header sections but instead jumping to the end of the sections, creating confusion for users. I have attempted a couple of solutions; here is the first at ...

Parent/Child Relationships in Typescript

Unraveling the Parent/Child Directive Mystery in Angular2/Typescript As I delve into the world of Angular2/Typescript/javascript, there is still much for me to learn. My current project involves a card game where each of the 2 players holds a hand of 5 ca ...