Transmitting OfficeJS 2D Array via an Ajax Call

Struggling with sending a "large" table using OfficeJS:

functionfile.html loaded from manifest route

<script>
(function (){
"use strict";

Office.initialize = function (reason) {
    $(document).ready(function() {
        $("#send-data-button").click(send_data);
    });
};

function send_data() {
    return Excel.run( function(context) {
    var data = context.workbook.worksheets.getItem("SheetName")
                      .getRange("A1:K3673").load("values");

    return context.sync().then( function() {
        // 2d table is correctly seen
        // $("body").append(data.values);

        // Just gets lost in ajax call
        $.ajax({
           type: "GET",
           url: mysite,
           data: {"accessData": data.values},

         }).done( function(success) {
            $("body").append("All Done");

         }).fail( function(error) {
            $("body").append("Error == " + JSON.stringify(error));
         });

         return context.sync();
    });
    });
}
})();
</script>
<div> <button id="send-data-button"> Send </button></div>

Trying to send this data, but facing challenges. I have a Flask server handling the request on the backside and was hoping to use pandas.read_json. However, no matter how I attempt to send it, various errors occur. When evaluating flask.request with data.values[0][0], here's what I get:

CombinedMultiDict([ImmutableMultiDict([('update_date', '43191'), ('accessData', 'Channel')]), ImmutableMultiDict([])])

Furthermore, when evaluating data.values[0], I receive an expected list of values:

CombinedMultiDict([ImmutableMultiDict([('update_date', '43191'), ('accessData[]', 'Channel'), ... <All my column headers>, ImmutableMultiDict([])])

But attempting to send the 2D array with just data.values results in an error message within ajax.fail:

Error == {"readyState":0,"status":0,"statusText":"error"}

Similarly, trying JSON.stringify(data.values) yields the same error message:

Error == {"readyState":0,"status":0,"statusText":"error"}

I even attempted converting each column into some kind of nested keys list inside accessData, but encountered the same error message. Any assistance would be highly appreciated.

Answer №1

It's best practice to separate the process of retrieving data from Excel and making an ajax call. Currently, these two tasks are mixed together, complicating the debugging process and creating a less organized structure.

For fetching data from Excel, you can use the following code:


function getExcelData(){
    return Excel.run( function(context) {
        var data = context.workbook.worksheets.getItem("SheetName")
            .getRange("A1:K3673").load("values");
        return context.sync()
            .then(function() {
                return data.values;
            });
    })
}

This approach allows you to then proceed with:


    getExcelData().then(function(values) {
       $.ajax(...)
    });

Keep in mind that range.values simply returns a standard 2D array. This means you can test your ajax call independently from the Excel fetch (another reason to keep these processes separate)

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

Implement the HTML code for utilizing the GET method in an AJAX request

I'm exploring a way to utilize inline HTML directly as the URL for the ajax GET method without fetching data from a separate webpage. Is it feasible? Here is my ajax code: $.ajax({ type: "GET", url: $(elm).attr("href"), ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

JavaScript Autocomplete - retrieving the value of a label

I am looking for a way to utilize the autocomplete feature in my form box to extract a specific value from the displayed label. When a user selects an option, I want to include part of the label (client_id) in the form submission process. JS: <script ...

Generate a text string by choosing options from a form

Greetings! I have a form for creating a file, where the file name is determined by user selections. It's similar to "display text as you type" mentioned here, but my form includes radio buttons in addition to a textbox. For example: Textbox: "Name gi ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload ima ...

Creating a standalone executable for Node.js without including the entire Node.js framework

Trying to pack a simple hello world script into an executable has led to some challenges. Both pkg and nexe seem to include the entirety of Node.js in the output file, resulting in quite larger files than necessary (around 30 MB). Although EncloseJS was fo ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

What is the best way to conceal the legend in a chart.js component within a React application?

I've been struggling to hide the legend on my Chart.js chart. Per the official documentation (), hiding the legend requires setting the display property of the options.legend object to false. I attempted the following approach: const options = { ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Scrolling automatically to a DIV is possible with jQuery, however, this feature is functional only on the initial

I'm currently working on a Quiz site and I've encountered a puzzling issue. Since the explanation only appears after an answer is selected - essentially a "hidden" element, I decided to wrap that explanation into a visible DIV. The code I'v ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Utilizing mapped data to display numerous Material-UI Dialog elements

On my table, I have a list of users displayed. Each user has a button in their row to delete them. Clicking the delete button triggers a Material-UI Dialog to confirm. An issue arises where 3 dialogs are being rendered due to mapping, and the last dialog ...

Is it possible to return PHP parser errors as JSON data?

I am facing an issue with my HTML page that uses a JQuery Ajax call to communicate with a PHP page and expects a JSON response. If the PHP encounters a parser error, it sends back the error message but not in the expected JSON format. This leads to a "JSON ...

Optimizing express server dependencies for a smooth production environment

After developing an application with a React front end and a Node server on the backend, I found myself wondering how to ensure that all dependencies for the server are properly installed when deploying it on a container or a virtual machine. Running npm ...

How can I achieve the functionality of an image changing when clicked and going back to its original state upon release with the help of HTML

I am facing an issue with styling an element to look like a button and function as a clickable link. My goal is to create a visual effect of a pressed button when it is clicked, while also loading the target page. For reference, here is a (non-working) J ...