What are some effective strategies for ensuring that DataTables search functionality integrates smoothly with AJAX results?

I am currently working on implementing a search function with DataTables, but I am facing issues with filtering the results from the table. Despite going through the documentation, something seems to be off.

I am fetching data using an AJAX call for this functionality.

The HTML snippet includes the search input field along with the accompanying jQuery code, but I am unable to identify what's missing in my implementation.

There are no error messages being displayed; however, the table data is not getting filtered as expected.

HTML

<div class="row d-flex align-items-end flex-column">
  <div class="col-sm-12 col-lg-4">
    <input type="text" class="form-control" id="myInput" placeholder="Search">
  </div>
</div>

<table id="tblData" class="table table-striped tabled-bordered" style="width: 100%">
  <thead>
    <tr>
      <th>Term</th>
      <th>Course Title</th>
      <th>Class No</th>
      <th>Session</th>
    </tr>
  </thead>
</table>

jQuery

//DataTables
$(document).ready(function() {
  $.fn.loadDataGrid = function() {

    $('#tblData').DataTable({

      orderCellsTop: true,
      fixedHeader: true,
      pageLength: 10,
      responsive: true,
      dom: 'tip',
      columnDefs: [
      {
        targets: [0],
        sortable: true,
        data: 'semester',
        width: '10%'
      },{
        targets: [1],
        sortable: false,
        data: 'title',
        width: '10%',
      },{
        targets: [2],
        sortable: false,
        data: 'class_nbr',
        width: '10%',
        className: 'dt-head-center dt-body-center'
      },{
        targets: [3],
        sortable: false,
        data: 'session',
        width: '10%',
        className: 'dt-head-center dt-body-center'
      }],
      order: [0, 'desc'],
      ajax: {
        url: 'data/ajax/file.cfm',
        dataSrc: '',
        error: function(xhr, error, code) {
          $().showMsgInfo('Sorry, there was a problem trying to retrieve the data. Please try again later.');
        }
      },
    });    
});

//search function
$(document).ready(function() {
  var table = $('#tblData').DataTable();
   
  // #myInput is a <input type="text"> element
  $('#myInput').on( 'keyup', function () {
      table.search( this.value ).draw();
  });
});

Answer №1

It appears that the variable table is being referenced in your filter without being defined.

Additionally, there is potential to simplify the code by consolidating it within one document ready function and removing the wrapping function for the DataTable declaration.

$(document).ready(function() {

  //initialize DataTable and assign it to a variable
   var table = $('#tblData').DataTable({

      orderCellsTop: true,
      fixedHeader: true,
      pageLength: 10,
      responsive: true,
      dom: 'tip',
      columnDefs: [
      {
        targets: [0],
        sortable: true,
        data: 'semester',
        width: '10%'
      },{
        targets: [1],
        sortable: false,
        data: 'title',
        width: '10%',
      },{
        targets: [2],
        sortable: false,
        data: 'class_nbr',
        width: '10%',
        className: 'dt-head-center dt-body-center'
      },{
        targets: [3],
        sortable: false,
        data: 'session',
        width: '10%',
        className: 'dt-head-center dt-body-center'
      }],
      order: [0, 'desc'],
      ajax: {
        url: 'data/ajax/file.cfm',
        dataSrc: '',
        error: function(xhr, error, code) {
          $().showMsgInfo('Sorry, there was a problem trying to retrieve the data. Please try again later.');
        }
      },
    });

    $('#myInput').on( 'keyup', function () {
      table.search( this.value ).draw();
  });

});

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

Troubleshooting: Issues with VueJS Class Binding Functionality

In my form, I have an input field that is validated to check if it is empty or not. If the input field is empty, a red border is applied using class binding. However, when the user focuses on the input field after receiving the error, the error message sh ...

Text input appearing on top of each other within the multiline TextField component in Material-UI

I'm experiencing an issue where the input text in a Material-UI Multiline TextField is overlapping. It seems to happen when I increase the font size to 30 but the line-height or some other factor remains set for the default font size. For reference ...

Issue encountered when attempting to generate a mongoose schema using a JSON document

Can I define this JSON file structure as a mongoose schema? Mongoose lacks an object type, and I'm unsure how to proceed with it. { "Moutainbike": { "Cross": { "size": [ "395 mm", "440 mm", "480 mm", "535 mm" ], "color" ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

When transferring JSON to JavaScript within Laravel, the JSON data gets converted into HTML entities by JavaScript

Within my Laravel controller, I am constructing a multidimensional associative array: $trendChart = Array ( "series" => Array ( "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5) ), "xaxis" => Arr ...

Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code. Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array. Al ...

"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :) Screenshot: ...

Storing information in a database using an array in PHP

Working with a PHP form, here is the layout: <form action="" method="post"> <table id="user-data"> <tr> <td>Firstname</td> <td>Lastname</td> <td>Age</td> ...

Modifying an HTML list item to become 'active' in a navigation bar

One way I've been implementing my navbar on each page is by using the following code at the bottom of the page within script tags: $("#navbar-partial").load("navbar.html). The code for the navbar list looks like this: <ul id="main-nav" class="nav ...

The string that matches the duration of hour, minute, and second (HMS)

There is a need to extract the digits before h, m, and s into their own groups. The objective is to capture all three groups if possible, but if one or two groups are missing, then the last group(s) should be captured. Currently, the regex /(\d+)(?=h ...

Transform a dynamic web page into a static one using Next.js

Utilizing Next.js and React.js, I create dynamic web pages. Specifically, I generate user-related web pages that need to be updated when there are changes in the user data. How can I generate static HTML pages from this updated data within Next.js? Are the ...

Can you explain the meaning of `bind(this)`?

Understanding how bind works is essential for binding objects or functions to desired functions. However, the usage of bind(this) can be perplexing. What exactly does this refer to in the context of the bind function? Here is an example of code snippet fr ...

How can JavaScript be used to access response header information in Devise Token Auth?

Currently, I am in the process of developing a web application using Rails as the backend API and Vue.js as the frontend library. For authentication purposes, I have integrated the devise_token_auth library. However, I am facing difficulty in retrieving th ...

Knockout.js Introduction - Identifying the Reason for Data Binding Failure

Trying out the most basic example of Knockout.js as showcased on their documentation page: I've followed the documentation instructions to set everything up correctly, and there are no errors showing on the page. However, the span that should display ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

Storing data from multiple pages onto the final page using C# and ASP.Net - step-by-step guide!

I need assistance with saving an application that spans across multiple pages. Instead of saving after each step, I would like to review a summary of all the pages on the final page before saving the complete application. Can someone please guide me throug ...

Unlocking the potential of NextAuth.js by enhancing the user session with additional database information on authentication

Currently, I am in the process of creating a straightforward credentials sign flow using next-auth ^4.24.5 with a nextjs 14 app. Within my user model, there is a boolean property named 'isAdmin' that I wish to make accessible in my session using ...

Is there a more secure alternative to using the risky eval() function? Do I need to take the lengthier route by implementing a switch case instead?

I've been practicing and honing my Javascript skills by working on a calculator code that initially had lots of repetitive lines. I managed to simplify it, but I am aware that using the eval() method is not generally recommended. let current = 0; f ...

Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ] <table> <tr class="row"> <td class="column"> <br> ...

Utilizing elapsed time in coding to create a function for DOM manipulation

As a new software engineering student, I am facing a challenge that I am struggling to overcome. I am currently working on developing a basic rhythm game similar to Guitar Hero using HTML, CSS, and JavaScript. I have successfully implemented an elapsedTim ...