Efficiently Incorporating JavaScript Variables into DataTable's aoData

I am facing an issue with a variable named search_gen, which is generated through an ajax request (shown below).

var search_gen;
$.ajax({
    type: "POST",
    url: link+module_name+'search_generator/'+module_active,
    dataType: "text",
    async: false,
    success: function(data){
        search_gen = data; //or something similar
    }
});

For example, this variable will contain JSON data (shown below)

{"name":"room_type_name","value":$("#room_type_name").val()},{"name":"room_type_code","value":$("#room_type_code"
).val()}

If I directly place the JSON data without using a variable, it works fine as demonstrated in the code below

table=$('#table').dataTable({
  "sScrollY": "400px",
   "bFilter": false,
  "bProcessing": true,
    "bServerSide": true,
    "sServerMethod": "GET",
    "sAjaxSource": link+module_name+'populate_list/'+module_active,
    "iDisplayLength": 25,
    "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
    "columnDefs": [ {
           "targets": 0,
           "orderable": false
           },
           {
           "targets": -1,
           "orderable": false
           } ],
  "fnServerParams": function (aoData) {
    aoData.push({"name":"room_type_name","value":$("#room_type_name").val()},
                 {"name":"room_type_code","value":$("#room_type_code").val()})
                }
})

But when I try to use the variable within the aodata.push() bracket (as shown below)

  table=$('#table').dataTable({
      "sScrollY": "400px",
       "bFilter": false,
      "bProcessing": true,
        "bServerSide": true,
        "sServerMethod": "GET",
        "sAjaxSource": link+module_name+'populate_list/'+module_active,
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "columnDefs": [ {
               "targets": 0,
               "orderable": false
               },
               {
               "targets": -1,
               "orderable": false
               } ],
      "fnServerParams": function (aoData) {
        aoData.push(search_gen)
}
    });

It results in an error like this. enter image description here

My question is, how can I correctly pass the variable search_gen into aodata.push()?

Thank you

Answer №1

It seems like you might be making the mistake of not waiting for the initial AJAX call to finish before invoking .dataTable. You can rectify this by using the code snippet below:

var search_gen;
$.ajax({
    type: "POST",
    url: link+module_name+'search_generator/'+module_active,
    dataType: "text",
    async: false,
    success: function(data){
        search_gen = data; //or something similar
    }
}).done(function( data ) {
  table=$('#table').dataTable({
      "sScrollY": "400px",
       "bFilter": false,
      "bProcessing": true,
        "bServerSide": true,
        "sServerMethod": "GET",
        "sAjaxSource": link+module_name+'populate_list/'+module_active,
        "iDisplayLength": 25,
        "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "columnDefs": [ {
               "targets": 0,
               "orderable": false
               },
               {
               "targets": -1,
               "orderable": false
               } ],
      "fnServerParams": function (aoData) {
        //aoData.push(search_gen)
        Array.prototype.push.apply(aoData,search_gen); // <<<<<<<<<<<<<< use this
      }
    });
});

Another approach is to call .dataTable within the success callback of the initial $.ajax call and utilize the data parameter instead of search_gen, like aoData.push(data).

UPDATE:

Based on your input, it appears that search_gen is an array. In this case, you should use

Array.prototype.push.apply(aoData,search_gen);
instead of aoData,.push(search_gen);. Please review the modified code above.

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 making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

The submission of the form is not functioning correctly when triggered by JavaScript using a button

My website was designed using a CSS/HTML framework that has been seamlessly integrated into an ASP.NET site. Within a ContentPlaceHolder, I have implemented a basic login form. The unique aspect is that I am utilizing the onclick event of an image to subm ...

Trouble with loading Google chart data from a local JSON file

The Issue Running multiple charts on a site simultaneously is causing page blocking while loading all the data before rendering the charts. The goal is to trigger the render function for each chart as soon as the data is available, rather than waiting for ...

Make Bootstrap Panel Full Width with Highcharts Data

I am currently working on displaying graphs using the Highcharts library on three televisions. All televisions have a FULL HD resolution of 1920 x 1080. I have one Bootstrap panel containing a graph in the panel-body. <div class="panel panel-blue"> ...

Adding a stylesheet dynamically in Angular 2: A step-by-step guide

Is there a method to dynamically add a stylesheet URL or <style></style> in Angular2? For instance, if the variable isModalOpened is set to true, I want to apply certain CSS styles to elements outside of my root component, such as the body or ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

Generate Address from Latitude and Longitude

For my project, I am trying to convert latitude and longitude coordinates into an address. While the Google Maps API is a potential solution, it requires an XML Response which complicates the process. I came across this helpful thread on Stack Overflow d ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

Extract the text enclosed by two specific symbols within a string and add it to a new array

I have a string formatted as follows: var str = "-#A This text belongs to A. Dummy Text of A. -#B This text belongs to B. Dummy Text of B. -#C This text belongs to C. Dummy text of C. -#Garbage This string should be ignored" I am looking to convert this ...

Using jQuery, Ajax, and HTML together can create dynamic

Is there a way to run JavaScript functions in an HTML file that is loaded using AJAX? The HTML file contains both text and JavaScript, but only the inline JavaScript seems to work (like onclick="dosomething();return false"). The pre-defined functions wra ...

Performing a Node.js PUT call with specified parameters

Attempting to send a PUT request using the 'request' function to the following URL: request({ uri: 'http://apiurl.url/1.0/data?token=' + APItoken, method: 'PUT', data: [{ ...

What causes isomorphic-style-loader to generate a TypeError: Cannot read property 'apply' of undefined when utilized alongside CSS-Modules?

Currently, I am working on server-side rendering the application, and while the HTML and JS are loading fine, I have encountered an issue with my styles (.less | .scss) not being loaded. After some research, I believe that the problem lies in missing the i ...

What are the steps to ensure compatibility with relative paths when transitioning from v5 to v6?

In my application, there are scenarios where multiple routes must pass through a component before rendering specifics. Additionally, there are situations where something is displayed for the parent route and then divided for the children. It's crucia ...

stepper vue with previous and next buttons

I am trying to create previous and next buttons in Vue, but I am struggling a bit because I am new to learning Vue. I have some methods like this.activeIndex < this.activeIndex - 1 that I need to implement. Can someone help me with how to do this? cons ...

I am wondering about the proper method for deleting multiple records simultaneously in Ember Data

My current challenge involves managing a list of record IDs, such as [1, 20, 20]. The process of individually querying and deleting each item is proving to be quite inefficient. store.findRecord('post', 1).then(function(post) { post.deleteRec ...

When invoking the jQuery ".load('pageName')" method, HTML pages are not loaded from the application cache

I have been working on incorporating the html5 offline caching functionality into our html pages, and everything seems to be running smoothly with jQuery version 1.4. However, I encountered a problem when I upgraded to jQuery 1.8. Specifically, issues aro ...

Leveraging Jquery to retrieve multiple values for dynamic updating in HTML

As I ponder over this dilemma, a suitable title eludes me to encapsulate my query. Behold the code in question: $(document).ready(function() { setInterval(function(){ $.get('/battleship/update_game/{{info.gameid}}/{{user.username}}', ...

Two ng-click events are triggered within a nested ng-click

I am facing an issue with using the ng-click within a nested list under another list that also has a ng-click event. Here is my code snippet: <ul> <li ng-repeat="facet in node.Facets" ng-click="updateNav(facet.Action)" ng-cloak & ...

The inclusion of XML in the web service standard can be attributed to its long-standing status as a

In my exploration of web services through books and blogs, I've noticed that XML is often presented as the standard message format. However, it seems to me that JSON could also be a viable option for defining messages in web services. Why then is JSON ...