Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows:

[
{
       "port_code":"BOM",
       "cont_details_id":"9",
       "price":"44.000",
       "cont_price":"500",
       "cont_no":"11",
       "cont_size":"20",
       "cont_type":"GP"
},
{
       "port_code":"BOM",
       "cont_details_id":"10",
       "price":"87.000",
       "cont_price":"500",
       "cont_no":"22",
       "cont_size":"20",
       "cont_type":"GP"        
},
.....
.....
etc.,
]

I have tried to store this JSON data in datatables using jQuery, but it's not working as expected. When I click on the search button, nothing happens. Can someone please assist me with resolving this issue? Your help is greatly appreciated. Thank you.

$(document).ready(function() 
    {

    var oTable = $('#example').DataTable();

    $("#search").click(function()
    {
        $.post("invoice_ajax.php",
        {
            loc  : $("#location").val(),
            cust : $("#customer_details_id").val()
        },
        function(data)
        {
            $("#text").html(data);
            var s = JSON.parse(data);

                        for(var i = 0; i < s.length; i++) 
                        {   
                            oTable.fnAddData([
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id,
                            s[i].block_id
                            ]);
                        } // End For
        });
    }); 


    });

Answer №1

Your approach is almost correct, but you may encounter issues when using the old 1.9.x fnAddData method with a 1.10.x API. Here is a more suitable solution:

oTable.row.add([
   s[i].port_code,
   s[i].cont_details_id,
   s[i].price,
   s[i].cont_price,
   s[i].cont_no,
   s[i].cont_size,
   s[i].cont_type
]).draw();

Alternatively, you can use:

var oTable = $('#example').dataTable();
...
oTable.fnAddData([
   s[i].port_code,
   s[i].cont_details_id,
   s[i].price,
   s[i].cont_price,
   s[i].cont_no,
   s[i].cont_size,
   s[i].cont_type
]);

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

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

An efficient method for extracting targeted information from a JSON encoded string

While working on some code, I encountered the following output when echoing this piece of code: echo json_encode($_SERVER); Output Received: { "HTTP_CONTENT_TYPE":"application\/x-www-form-urlencoded", "HTTP_USER_AGENT ...

What is the best way to combine a hyperlink with a string in an Angular form?

Currently I am in the process of learning angular and experimenting with creating a list of websites that can be clicked on, similar to what you would find in a bookmark app. This is based on a todo example. https://github.com/LightYear9/ToDoList In orde ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Filtering JSON API response based on the name parameter

I've searched through numerous similar questions and discussions, but none have provided a solution to my problem. I am working with an API response that contains a list of jobs executed on a virtual machine. Specifically, I am interested in summarizi ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

HTML5Up! Skyrocketing with Meteor showers

While attempting to utilize a responsive site template from , I encountered several issues. To test the template, I downloaded the Striped package and created a clients folder in a Meteorite app where I placed the Striped folder. In order to make it work, ...

Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code: // Default Import Statements var Login = require(login.jsx) const HeaderComponent = React.createClass({ getInitialState () { return { loggedIn: false, }; }, render() { return ( ...

Enhance the efficiency of time tracking function

I have been using a nodejs module to track the execution time of different parts of my application. // polyfill for window.performance.now var performance = global.performance || {} var performanceNow = performance.now || performance.mozNow ...

I'm curious if the response order will mirror the URL order in my situation

QUERY: Upon reviewing the following link: Promise.all: Order of resolved values I am doubtful about its relevance to my specific scenario. Can I always expect responses to be in the same order as urls? EXAMPLE: var urls = []; for (var i = 0; i < d ...

Constant price updates through an API loop

I am transferring data from a spreadsheet to a dataframe that includes product details, which I need to update prices in an e-commerce via a put request through an API. However, I am facing the challenge of creating a loop to properly iterate through the e ...

Tips for embedding Javascript code within the window.write() function

I have a JavaScript function that opens a new window to display an image specified in the data variable. I want the new window to close when the user clicks anywhere on it. I've tried inserting some JavaScript code within window.write() but it doesn&a ...

Collaborating with two-way JACKSON communication channels

Apologies for my poor English; Below is the code snippet in question: @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class UserAccount implements Serializable { private static final long seria ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

Redux/React project bundle

I am currently attempting to incorporate the package https://www.npmjs.com/package/is-url into my React/Redux project, but I'm unsure about how to go about importing it. Are there any other ES6-compatible installation options that you would recommend ...

Symfony 2 and the power of asynchronous requests!

I'm facing a major issue because I am unable to make an AJAX request in Symfony. Below is some code snippet from my template: $( document ).ready(function() { $( ".data" ).change(change_selected); }); function change_selected(){ $.ajax({ ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...