selecting the ajax url for the datatable

I need to select the datatable ajax URL based on whether it contains data1, data2, or data3.

Below is my code snippet:

$(document).ready(function() {
var $table = $('#datatable1');
    $table.DataTable({
      "columnDefs": [
                     {"className": "dt-center", "targets": "_all"}
                    ],  
   if(containdata1){
   ajax: {
           url: "/api/dunapi/"+containdata1,
                type: 'GET'
            },

   if(containdata2){
    ajax: {  
        url  : "/api/dunapi/"+containdata2,
        type : 'GET'                      
            },
   
   }
   if(containdata3){
    ajax: {  
        url  : "/api/dunapi/"+containdata3,
        type : 'GET'                      
            },
   
   }

I am looking for a solution where the ajax URL selection can be dynamic based on the data available.

Answer №1

If you're looking to combine data from multiple sources, a good approach would be to fetch the data outside of DataTable. Utilize jQuery's ajax() function (or another JavaScript client like axios) to retrieve all the necessary data, merge it into a single object, and then pass it into the data option of DataTables.

For example:

var data = []

if(containdata1){
    await axios.get("/api/dunapi/"+containdata1).then(res => {
        data = data.concat(res.data)
    })
}
if(containdata2){
    await axios.get("/api/dunapi/"+containdata2).then(res => {
        data = data.concat(res.data)
    })
}
if(containdata3){
    await axios.get("/api/dunapi/"+containdata3).then(res => {
        data = data.concat(res.data)
    })
}

Then when defining your datatable:

{
// include other datatable options
data: data
.....
}

Note: Remember to add async before the ready function as we are using await in each request:

$(document).ready(async function() {
......
}

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

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

javascript guide to dynamically update the glyphicon based on value changes

I am attempting to implement an optimal level feature where a glyphicon arrow-up will be displayed if a value falls within the optimum range, and it will switch to a glyphicon arrow-down if the value is lower. <div class="card-body" ng-repeat="item i ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

"Improving User Experience with React.js Serverside Rendering and Interactive Event Handling

Currently, I am in the process of learning how to utilize react.js but I am facing some challenges with using event handlers. Here's a question that has been lingering in my mind: Is it feasible to employ server-side rendering and automatically send e ...

Error: Attempted to call $scope.map.control.getGMap function when clicking on the Map, but it is not defined

I'm currently working with Angular-Google-MAP and I'm trying to add a marker to the map. However, whenever I click on the map, I receive an error message saying $scope.map.control.getGMap is not a function. This error is occurring within the geoc ...

Adding text after a div in React-JS using Bootstrap: A quick guide

Just starting out with website development and I have a question. As I practice making this website, I am struggling to figure out how to add the text "To know more about us click here" below the 'Get started' button. I tried adding a simple < ...

There seems to be a complete absence of rendering in this particular vue

Upon initializing a fresh Vue project using Vue CLI 3 and removing all default views and components, I proceeded to add two new views. To my surprise, these views did not render when changing the URL; instead, I was met with a blank page and no error messa ...

Is there a way to restrict the number of checkboxes selected based on the values of radio buttons?

I am currently working with a group of radio buttons: <input type="radio" name="attending_days" value="06-18-13"/>Tuesday June 18, 2013 <input type="radio" name="attending_days" value="06-18-13"/>Wednesday June 19, 2013 <input type="radio" ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

Guide on capturing JSON objects when the server and client are both running on the same system

I created an HTML page with a form that triggers JavaScript when submitted using the following event handler: onClick = operation(this.form) The JavaScript code is: function operation(x) { //url:"C:\Users\jhamb\Desktop\assignmen ...

Transforming arrays into nested objects using JavaScript

My array consists of objects structured like this: var exampleArray = [{ name: 'name1', subname: 'subname1', symbolname: 'symbol1' }, { name: 'name1', subname: 'subname11', symbolname: 'sy ...

Which is better: JavaScript, Json, or Html?

When working with an ASP.NET MVC view and using jQuery AJAX to update a div, the decision on whether to use a controller that returns a PartialView or JSON can depend on various factors. Consideration for both user experience and system performance is im ...

Display customized modal content in React based on specific criteria

I have a list of product partners with a "Know More" link that opens a modal. I'm trying to figure out the best way to pass props to the modal in order to display the correct partner's information. Here is the code snippet related to this functi ...

Navigating to redirected URL within jquery's get() function

When I tried sending a get request to a Google App Script URL in my application using JQuery's get method, everything was working fine. However, out of the blue, that API started redirecting to a different URL in case of an authentication error. As a ...

creating a function within an object that allows for chaining

My goal is to create a chainable object, but I am struggling to implement this in a function. This is the functionality I desire: $donate.ga('testing').go(value); The code for my object currently appears as follows: var $donate = { ga: fu ...

Loading JavaScript in the background using Java and HtmlUnit

I am currently facing a challenge while navigating a website using HtmlUnit. This particular website adjusts certain buttons and displays or hides certain elements based on JavaScript events. For instance, there is a text input box along with a button th ...

When using jQuery to add an item to a List, it disappears immediately after

I am facing an issue with the code I have. Whenever I click on the "Add" button to add an item, it briefly appears in the list but then disappears. I'm having trouble figuring out why this is happening. $(document).ready(function() { $("#submitB ...

Mobile devices are unable to properly implement the Jquery show/hide feature

Currently, I am working on a small Russian project and facing some challenges with the mobile version of my website: php8098.github.io/breakfast. The issue lies within the first slider where the play button should trigger a modal window to open. I urgentl ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

Encountered an issue with the Mongoose Schema method: The model method is not recognized as a

Here are two Mongoose model schemas that I am working with. The LabReport model includes an array that references the SoilLab model. Within the SoilLab model, there is a static method that was initially used to choose which fields to display when retrievin ...