Handling Ajax response in datatable

While working on a project that involves integrating DataTables and Excel files, I encountered the challenge of uploading an Excel file and displaying its contents using DataTables. Despite my search for a JavaScript library that could parse the Excel file and seamlessly integrate it with DataTables, I found no suitable solution. The only viable option seemed to be sending the data to the front-end server using Struts/Java, processing it, and then returning it as JSON. I wonder if there is a way for DataTables to wait for the JSON data via Ajax without explicitly making a request.

Answer №1

In my opinion, accomplishing this task is feasible using HTML5 and JavaScript. To test it out, just execute the following code:

<html>
</head>
<script>
  function readBlob() {

    var files = document.getElementById('files').files;

    if (!files.length) {
      alert('Please select a file!');
      return;
    }

    var file = files[0];
    var start = 0;
    var stop = file.size;

    var reader = new FileReader();

    // If we use onloadend, we need to check the readyState.
    reader.onloadend = function(evt) {
      if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        document.getElementById('byte_content').textContent = evt.target.result;
      }
    };

    var blob = file.slice(start, stop);
    reader.readAsBinaryString(blob);
  }

</script> 
</head>

<body>
<input type="file" id="files" name="file" accept=".csv"  />
<span class="readBytesButtons">
  <button onclick="readBlob()">entire file</button>
</span>
<div id="byte_range"></div>
<div id="byte_content"></div>
</body>

</html>

With the help of FileReader in JavaScript, extracting Excel data as text is achievable. For displaying the data in a datatable format, your own logic must be applied.

Answer №2

Sure, absolutely!

Perhaps you're interested in attempting something along these lines:

  1. Start by uploading the file to the server

    • In your Struts action, read the Excel file, save it temporarily on the disk, and return the file name to your JSP.
  2. Once the first step is completed, initiate an Ajax call to the Struts action

    • Pass the file name as a parameter in the Datatable Ajax call
    • Retrieve the file from the disk, read it, and populate a Pojo or VO object with the data
    • Generate JSON from the Pojo using Gson or Jackson API
    • Finally, return the JSON response

To delve deeper into this topic, check out this resource on Datatable AJAX sourcing

Answer №3

Achieving this task is entirely feasible without the need for Ajax in your specific scenario. How can you accomplish it? Take a look at the steps below:

Start by setting up a form to upload the excel file to my struts framework. Proceed to process the excel file and display the contents in clean HTML/table structure. Finally, initialize a basic datatables setup upon page load to complete the process!

UPDATE

If you require pagination, consider utilizing datatables with Ajax capabilities as outlined below:

var oTable = "";
$(document).ready(function() {
  oTable = $('#htmltableID').dataTable({
    "sPaginationType": "full_numbers",
    "bServerSide": true,
    "sAjaxSource": "/myAjaxSource.jsp?page="+pageNumber+",
    "sServerMethod": "POST",
    "iDisplayLength": 50
  });
}

Within your myAjaxSource.jsp file, retrieve the page parameter sent via the ajax URL and provide the corresponding data (in JSON format)

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 properly formatting the sort_by parameter in Cloudinary to avoid errors

Greetings to the helpful stack overflow community, I have encountered an issue with fetching images from cloudinary via a post request. Everything works fine until I include the sort_by parameter in the URL. This results in an error related to the format ...

Tips for saving a document in a table without using the _id field

I want to save the employee object without the _id attribute, just the "employee" attribute as shown below: "employee" :[ { "name" : "leila", "idemployee" : ObjectId("59319505efa50b137477a1f4"), ...

Create a visual representation of a data structure using a JSON object in order to provide a comprehensive overview of the objects and their connections

Is there a way to create an SVG/PNG to illustrate the data structure of a JSON object? I remember generating images like the one in the attached file, but I can't seem to find the source anymore. I've searched on Google but couldn't find any ...

Unique index in Spring Data MongoDB is set to true

Struggling with Spring Data and MongoDB regarding an Indexed field. The documentation didn't provide clear explanations on the distinction between @Indexed(unique=true) and @Indexed(unique=false). I have a field that needs to be indexed for fast que ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Linking JavaScript on the client side to a NodeJS application on the server side

I am new to NodeJS and I am currently exploring the app structure. I have developed a basic app using Socket.IO and MongoJS, which functions as a tracking system that gathers variables from a client-side script and stores them in Mongo. This is how I envi ...

Capturing Exceeding JSON Length Limit in ASP.NET MVC Serialization

I encountered an issue when trying to return a large JSON result: The string length exceeds the maxJsonLength property value set. I attempted to catch the exception during serialization, but it doesn't work as expected. try ...

Having trouble locating and interacting with elements in the footer with Selenium Webdriver

I'm having difficulty selecting and clicking on an element located in the footer. Here is the code: https://i.sstatic.net/cFhTX.png I attempted to find the correct XPath using Chrome console. The codes I tried are below, but they are not highlighti ...

Develop a real-time preview of the form inputs

While working on a multistep form, I am exploring the idea of creating a live preview that shows values entered into different input fields, text areas, and radio buttons. Currently, I have successfully built the form and made some progress using the foll ...

Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page. As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen. ...

What is the best way to access a particular property of an object?

Currently, I am successfully sending data to Mongo and storing user input information in the backend. In the console, an interceptor message confirms that the data is received from MongoDB. However, I am struggling to extract specific properties such as th ...

Efficiently Indexing JSON Strings from Spark directly into Elasticsearch

Can JSON strings be directly indexed from Spark to Elasticsearch without using Scala case classes or POJOS? I am currently working with Spark, Scala, and Elastic 5.5. This is my current code snippet: val s = xml .map { x => import org.jso ...

Utilize jq to extract fields from objects that are nested across multiple levels

I have a file full of data records like the ones below: {"input":{"payload":{"id":"rec1","var2":"imp_val1","var3":"","var4":"000000"},"recordName" ...

Ajax causing unreliable posts

I am facing an issue with sending and receiving data in my mobile application. I currently use the jquery $.post function, but it seems to be quite unreliable. Issue: Occasionally, about 1 out of 10 times, the POST request is sent successfully, but the ca ...

Is it important that the end date does not exceed the start date?

In my request, the end date cannot be later than the start date. For example, if the start date is 24/4/2017 and the end date is 23/4/2017, the search function should be disabled for the calendar date 23/4/2017. Only dates from 24/4/2017 onwards should be ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

The functionality of the ajax hash navigation feature seems to be malfunctioning

I've been trying to use hashes for my navigation, but everytime the page loads, my script resets the initial hash to #home. It doesn't matter what hash I add in the URL: Here is the script that runs to check if the hash exists and what content t ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

Using a Function as an Argument to Return an Unnamed Object

There seems to be a common trend in JavaScript code where a function is passed as a parameter, which in turn returns an anonymous object. myFunction(function() { return { foo: 'bar' }; }); What benefits or reasons are there for u ...

restart form upon div closure via ajax

Is there a way to revert my form back to its original state upon closing a div? I'm currently utilizing ajax and django. A suggestion I received was to include a reset_recipe field in my form that, when set to true, resets the recipe. Below is my d ...