Dial the Google App Scripts hotline

After successfully testing the query string in the browser for my published app script, I attempted to send an XMLHttpRequest to the script. However, upon doing so, I encountered the following error message:

XMLHttpRequest cannot load https://script.google.com/macros/s/XXXXXXXXXX/exec. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://docs.google.com' is therefore not allowed access.

This snippet showcases the app script code utilized:

function doGet(e){
  Logger.log(e.parameter.id);
  //other function
  return ContentService.createTextOutput("Hello World");
}

Additionally, provided below is the client-side code utilized:

$.ajax({
    url:'https://script.google.com/macros/s/XXXXXXXX/exec',
    method:'POST',
    data:{
        id: "123123"
    },
    success:function(){
        console.log("success");
    }
});

Answer №1

Encountering this error is not uncommon, and I have faced it myself in the past. Since I lack the necessary reputation to leave a comment asking for clarification, I will attempt to identify the root cause.

The issue at hand consists of two main aspects - the inability to post unstringified objects and the absence of CORS headers on Google Apps Script errors.

solution: stringify and parse the object

If you do not convert the object into a string format, your browser will simply send [Object object] instead of the relevant information, leading to an error in your script. Error messages from Google Script are HTML webpages lacking CORS headers, thus triggering an erroneous CORS response that fails to pinpoint the actual problem.

In order to effectively POST the parameters, you must transform the object into a string using a method such as JSON.stringify(), extract the value via e.postData.contents within your Google Apps Script, parse it, and then utilize it as if it were an object.

I personally came across similar advice when researching about sending raw objects in JavaScript on this thread.

You mentioned successful testing with query strings in your browser, yet it is crucial to note that this triggers a GET request, activating the doGet function instead of doPost.

This explanation offers the most likely solution, and I hope it proves beneficial to you! Remember to test your code thoroughly with default values before deployment, as troubleshooting issues post-deployment can be quite challenging. You can utilize to investigate the output without encountering CORS errors along the way.

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

Getting to the values within a JSON object that contains multiple arrays

Is there a way to retrieve array data from the json object data? const [data, setData] = useState([]) const getData = () => { axiosInstance .get(url + slug) .then(result => setData(result.data)) } useEffect(() = ...

The AJAX data variable fails to send to PHP script although $_POST is defined

I am at my wit's end with this problem. I am attempting to send a variable to a PHP script using AJAX, and although I can confirm that $_POST is set, the variable remains undefined. Oddly enough, I have used almost the same code in other instances an ...

One method to add a hashtag before a variable in the HTML attribute value data-bs-target

Basically, I have set up a vue web application with a container containing multiple bootstrap cards. Each card has a button that is supposed to collapse a form for guests to apply. However, the issue arises when I click on the button of one card, as it col ...

Leap over in a similar fashion to the provided demonstration

In my attempt to create a unique project, I have created this CodePen example. The goal is to have one ball on the circle that remains in a fixed position, while another rotating main ball must avoid touching it at all costs. Points are awarded for success ...

Locate the midpoint index of the initial sequence occurrence within an array

I am trying to determine the midpoint of the first sequence that appears when given multiple strings in a large array For example: var array = ["c6dafc", "c6dafc", "1d2129", "1d2129", "1d2129", "cfcfff", "cfcfff", "ffffff", "1d2129", "1d2129", "1d2129", ...

Display exclusively on indexes 0 and 3

Here is the code snippet I am working with: {(type === 'NEW') && ((index === 0) || (index === 3)) && <hr className={styles.hr}/>} I would like to combine these conditions into a single expression that w ...

How should one properly handle JSON parsing in PHP?

After receiving a JSON string from a Node JS Service, I encountered an issue when trying to use json_decode() in PHP. The var_dump showed the string with extra characters and caused a syntax error. To resolve this, I attempted to replace some of the probl ...

Retrieving Mouse Coordinates using Ajax in PHP

I'm wondering if it's feasible to send an Ajax request with mouse coordinates using PHP. For instance, I am fetching a page with cUrl and would like to trigger a mouse movement event on that page. At this point, I haven't written any code ...

Closing the Bootstrap navbar collapse by clicking anywhere outside of the menu area

Excuse my lack of experience, but I have a question. I am trying to make Bootstrap "navbar-collapse" close when clicking away or on one of the list items. I stumbled upon this code that seems to do the trick. $(document).on('click',function() { ...

Using angularJS and Regular Expressions to eliminate the "+" symbols in an email address

I have been given the task of disallowing email addresses with a "+" sign from registering. As someone new to regex, my understanding is that it is better to focus on defining what constitutes a valid input rather than listing what should be excluded. I re ...

When the return false statement is included, the form fails to submit and instead refreshes on the current page

I recently discussed an issue regarding triggering a dialog box before confirming a submit action. Unfortunately, after implementing this, the document no longer submits when expected. Instead, it just remains on the same page with the same settings. I h ...

Issue with sending Ajax POST requests to MVC Controller

I'm encountering an issue with my Ajax request: $.ajax({ url: '/Projects/Index', type: 'POST', data: data, dataType: 'json', contentType: 'application/json; charset=utf-8', error: xhr =& ...

Using Web API Controller to trigger a JQuery function

Having searched through numerous posts, I was unable to find a specific discussion on integrating a Web API Controller into the MVC Framework. Therefore, I decided to create a post addressing this topic. In my case, I am working with C# and my controller ...

Issue with Click event not functioning after dynamically adding HTML via AJAX in Kendo UI

Currently, I am working with Kendo UI and encountering an issue when trying to implement an ng-click option on HTML content that is loaded dynamically. https://i.sstatic.net/AbEFP.png Below are the relevant sections of code: HTML: <div ng-controller ...

What might be causing the attribute of this Backbone model to be undefined when attempting to access it?

I have a straightforward REST API that provides information about an item at /api/items/:id, which includes the ID and name. I am using a Router to organize my Backbone views. The edit route creates a FormEditItem view, passing the ID from the URL. To ret ...

Is it possible that Helm3 converts a JSON file into a string when creating a configmap?

Issue Description: I am trying to import a json file into a configmap to be formatted like this: apiVersion: v1 kind: ConfigMap metadata: name: json-test data: test.json: |- { "key": "val" } However, I am encountering the following for ...

Automatically submit upon selecting an option

Encountering some difficulties with the code provided below. Purpose of this code I have multiple list items (shown here is just a snippet) made up of select elements, options, and one submit input field. When an option is chosen, the user can click on ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...

Getting the initial value of a node from a JSON response by utilizing Groovy

I am attempting to extract the first node value (ResourceItemID which is 2290) from my JSON response. Here is how my Response looks: { "Success": true, "TotalRecords": 41, "RoomSearchResult": [ { "ResourceItemID": 2290 ...

Display or conceal elements in a v-for select input by leveraging the value of another input with Vue3

In my form, I have two dropdown select option fields generated using loops from predefined constants. One dropdown is for selecting different "sides" and the other for choosing various "caps". When a user selects "2-Sided" in the sides dropdown, I want t ...