DataTables.js → How to update your data object for AJAX JSON data retrieval

DataTables!?

I love DataTables.js. It makes working with HTML tables a breeze and increases functionality such as search, sorting and pagination.

Their documentation is stellar, however, it’s still written by devs, so it doesn’t explain code to people like you and me. You know. Normal.

This is why I wanted to write the quick post about how to use dynamic data in your DataTables AJAX request.

The Code

Normally, you would instantiate your DataTable for ajax, like this:

//All code in these examples are written in jQuery
//Notice the code in BOLD
$('#example_table').DataTable({
  'ajax': {
    "type"   : "POST",
    "url"    : '/path/to/your/URL',
    "data"   : {
          "key_example1" : "value_example1",
          "key_example2" : "value_example2"
         },
    "dataSrc": ""
  },
  'columns': [
    {"data" : "metric_name"},
    {"data" : "metric_type"},
    {"data" : "metric_timestamp"},
    {"data" : "metric_duration"}
  ]
});

The Wrong Way

It took me a min to figure out this is how they wanted you to send the data, as their documentation makes it seems like you would write something like:

example_table.ajax.data({//object properties here});

However this way doesn’t work at all and simply throws errors.

The Right Way

Now what’s really nice about DataTables is the ability to use a function for that data property :

var example_table = $('#example_table').DataTable({
  'ajax': {
    "type"   : "POST",
    "url"    : '/path/to/your/URL',
    "data"   : function( d ) {
      d.example_key1= $('#example_input1').val();
      d.example_key2= $('#example_input2').val();
      d.example_key3= $('#example_input3').val();
    },
    "dataSrc": ""
  },
  'columns': [
    {"data" : "metric_name"},
    {"data" : "metric_type"},
    {"data" : "metric_timestamp"},
    {"data" : "metric_duration"}
  ]
});
//To Reload The Ajax
//See DataTables.net for more information about the reload method
example_table.ajax.reload()

As you can see, you simply can see any property of the parameter “d” and set a value. DataTables will then set the “data” object to those properties.

For example, if the values of example_input1, example_input2, or example_input3 change, simply reload the ajax method of DataTables by using :

example_table.ajax.reload()

and your table will perform the ajax call along with the new values provided.

Happy Coding!

Remove a Class from an HTM Element

To remove a class from an element, you use the remove() method of the classList property of the element.

Suppose you have a <div> element as follows:

<div class="primary visible info">Item</div>

To remove the visible class from the div element, you use the following code:

const div =  document.querySelector('div');
div.classList.remove('info');

The remove() method also allows you to remove multiple classes at once, like this:

const div = document.querySelector('div');
div.classList.remove('info','primary');

Here is another example using jQuery selector;

Let’s say we have these classes;

 <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" id="spanCount">
    99+
    <span class="visually-hidden">unread messages</span>
 </span>

We are going to select span HTML element with an id of “spanCount”. We will remove badge rounded-pill and bg-danger classes;

const spanElement = $("span#spanCount");
console.log(spanElement)
$("span#spanCount").removeClass("badge rounded-pill bg-danger");

Sources

jQuery selectors

Add, Remove classes

The character + is converted into “&#x2B” in base64 encoded data

I am passing following string from MVC component (c#) to razor view;

var Count = "99+";

When I try to access this in razor view, i get &@x2B appended to it;

console.log(@Model.Count);
///
///--output
99&#x2B

Razor does some encoding. To get ride of this problem, we need to use @Html.Raw.

console.log(@Html.Raw(Model.Count)
///
///--output
99+

or better, use it with backtick operator;

let count = `@Html.Raw(Model.Count)`;
console.log(count);
///
///--output
99+

enjoy!

The Intersection Observer API: Practical Examples

This article demonstrates using the Javascript Intersection Observer API, instead of measuring scroll position, to perform common visibility detection tasks.

The Problem

In Javascript, performing an action when an element becomes visible to a user has previously always required the following:

  1. Detecting the current scroll position. Setting an event listener to do this is easy enough, but the performance overhead can be costly. You will almost always want to write a throttling function to limit the amount of events fired when a user is scrolling. If you don’t know how to write this yourself, then you might reach for a library like Lodash, etc. which adds another dependency to your codebase.
  2. Getting the top offset. Select the element you want to observe in the DOM and get its top offset relative to the element (or viewport) you are detecting. This may seem straightforward until you factor in any lazy loaded or async loaded content. Once you finally have that number, don’t forget to recalculate it because that pesky banner image loaded in at the last second and skewed your original number.
  3. Unset and cleanup. Once you run your logic, you need to remember to remove the event listener. Sometimes you may have several.
  4. Beware of main thread work. The function you pass to the event listener will be running on the main thread, and will be running hundreds or possibly thousands of times until your condition is met, even with the throttling you hopefully put in place.
  5. Other use cases. Last but not least, there are scenarios where you may want to detect when an element is about to become visible, or after a user has scrolled past an element by a certain threshold. This would require more changes to the logic above.

The Solution

The Intersection Observer API is an excellent solution to this problem. It’s a fairly recent browser API that lets developers hand most of these tasks off to the browser, in a way that is more optimized.

For more info, click here

Old techniques are here;

https://demos.flesler.com/jquery/scrollTo/