Having difficulty grasping the concept of integrating Google Sheets API into my project

Being a newbie in web development, I am trying to extract data from a Google sheet and visualize it within a Javascript-animated canvas object.

However, navigating through the Google Sheets API documentation has been quite challenging for me. Although my basic GET application worked fine on a local Python server, I encountered an error when testing it on a hosted website. The error message starts with 'Load denied by X-Frame-Options', indicating a possible JSONP issue. Strangely, there is no clear explanation in the documentation on how to handle this as JSONP. Despite making the spreadsheet public, authentication still seems to be required.

Below is the code snippet without IDs:

 <script>         

      var CLIENT_ID = 'my_client_id';

      var SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];

            function checkAuth() {
        gapi.auth.authorize(
          {
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
          }, handleAuthResult);
      }

 /**
       * Handle response from authorization server.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {

        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.

          loadSheetsApi();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
    console.log('nope');
        }
      }

      /**

      /**
       * Load Sheets API client library.
       */
      function loadSheetsApi() {
        var discoveryUrl =
            'https://sheets.googleapis.com/$discovery/rest?version=v4';
        gapi.client.load(discoveryUrl).then(trackDonations);
      }

      /**
       * Print values in the donations column
       */
      function trackDonations() {
        gapi.client.sheets.spreadsheets.values.get({
          spreadsheetId: 'my_sheet_id',
          range: 'Form Responses 1!C2:C',
        }).then(function(response) {
          var range = response.result;
          if (range.values.length > 0) {
              console.log(range.values);
            $('.sum').text(range.values[range.values.length-1]);
          } else {
            prompt('No data found.');
          }
        }, function(response) {
          prompt('Error: ' + response.result.error.message);
        });
      }



    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">

I might be overlooking something simple, so any guidance on this would be greatly appreciated! Thank you!

Answer №1

For those tackling a spreadsheet project, consider utilizing AppsScript for smoother functionality.

To get started, navigate to Tools > Script Editor within the spreadsheet interface. This tool allows you to efficiently load data into an array using https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getDataRange() and serve it as jsonp by following this guide https://developers.google.com/apps-script/guide/content#serving_jsonp_in_web_pages. Upon choosing 'Deploy as web app' (depicted by a cloud icon), a designated URL will be provided for embedding in your code.

This method mirrors the rest API approach but grants users enhanced control over response mechanisms.

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

The identical function syntax only functions properly when it is directly copied from an external source code

Currently, I am going through a React tutorial. Within the Backdrop.js file, there is a straightforward function that generates a backdrop and attaches an onClick event handler to close an open Modal when the user clicks on the backdrop. Oddly enough, eve ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Adjust the level of output from webpack when initiating the vue-cli-service serve programmatically

My current challenge involves executing the vue-cli-service serve command within a Node.js application as shown below: const Service = require('@vue/cli-service'); const service = new Service(process.cwd()); service.init("development"); service. ...

Using ReactJS: Injecting components and passing variables in extended components without the need for functions

Currently, I am utilizing apollo for the authentication process in my nextJS application. My next task is to incorporate i18n support, but I am encountering some fundamental issues: The primary obstacle lies in handling class Index extends React.Component ...

Can PHP convert a value object or data transfer object into JSON using a built-in method?

Is there a way to transform a value object, such as the one shown below, into an array or JSON without manually building it? class Vo { private $blah; private $de; public function setBlah($blah) { $this->blah = $blah; } ...

Revamping perspectives: the art of transferring values from a list to each individual map

I have been struggling with the jolt transformation and need help finding a solution I want each attributeList to have attributeType and attributeValue, along with a unique modelId where key names are case sensitive in the expected output Input [ { ...

Different ways to convert a Plain Old Java Object (POJO) to JSON using Jackson

I am facing a challenge in serializing a POJO differently based on the value of one of its properties. Specifically, I want to include NULLs when "show" is true and exclude NULLs when "show" is false. It's important to note that the actual object I am ...

Verify input submission using jQuery UI

I'm in the process of verifying a submit form that has been created using Ruby on Rails. Prior to submitting, I have implemented a condition that triggers a confirmation popup asking the user if they truly wish to proceed. Initially, this was function ...

The function attached to the `click` event of `#cart-continue` is not invoking

I'm currently working on implementing a navigation to a specific anchor tag when the user clicks the continue button on the cart page. This project involves a mobile application built with Cordova, and the function call is done using jQuery. Here is ...

Accessing values in a JSON object using C#

How do I extract a value from a JSON Object? Should I convert it into a class or can I retrieve it directly from the .json text file? Here is an example of the JSON file I have created: { "801": { "Name": "Tarlac", & ...

Having trouble sending POST requests in Express?

I developed an API and all the routes were working perfectly until now. However, when I attempted to send a POST request to the "/scammer" route, I encountered the following error message: Error: write EPROTO 1979668328:error:100000f7:SSL routines:OPENSSL_ ...

Error message: Unable to access .exe file through HTML link

We have a need to include an HTML link on our intranet site that, when clicked, will open an .exe file that is already installed on all user machines. I attempted the following code: <a href = "C:\Program Files\Cisco Systems\VPN&bsol ...

Implement the charset meta tag using JavaScript

Currently troubleshooting a bug that seems to be related to the browser defaulting to the user's native charset (ISO-8859-1) instead of UTF-8. Here is the link for more information: https://github.com/OscarGodson/EpicEditor/issues/184#issuecomment-880 ...

Requesting data from a REST API using a nested query in a GET

After querying data from my MongoDB database, I am faced with the challenge of sending a GET request from the front end to meet this specific query. In my backend code, I retrieve the data using the following: const products = await Product.find({ &apo ...

Adjusting AngularJS scroll position based on key presses

I am currently working on an autocomplete feature using AngularJS. I seem to be experiencing a problem with the scrollbar behavior. In the interactive gif provided, you can observe that the scrollbar remains stationary when navigating with the arrow keys. ...

I am finding my program to be lacking efficiency. Is there a more concise method for solving this issue?

Starting off with my journey in Javascript, I am eager to tackle problems and enhance my skills. One challenge that came my way is the following question. Despite my efforts to solve it step by step, I feel like there might be room for improvement in my co ...

Components loading in Angular result in lat long being undefined in google map integration

I am currently utilizing Ionic-angular AGM. I am facing an issue where I am unable to retrieve my current location when the component loads, as it seems like the component is being fired before the latitude and longitude are ready. How can I make this proc ...

Following an ajax request, the tooltip feature in bootstrap fails to function properly

I am currently facing an issue with my files. I have an index.php file where I include another file named file1.php (which consists of all the necessary files for jQuery, js, etc.). Within file1.php, there is a table with buttons that trigger modals. The i ...

What is the method for adding an event listener in AngularJS within an ng-repeat iteration?

I'm completely new to AngularJS and currently working on building a photo gallery. The basic idea is to have an initial page displaying thumbnail photos from Twitter and Instagram using an AngularJS ng-repeat loop. When a user hovers over an image, I ...

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...