Send information to a Google form using AJAX requests

I have encountered an issue while attempting to send data via AJAX to a Google form. Despite receiving a success message with a statusCode of 0, the data does not show up in the form:

var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"};
postToGoogle("1FAIpQLSf4w1OQGsIncaiqXlmfAl4jYSt-e4Zx3xVJa7Weob4LnQbRZQ",dat);

function postToGoogle(id, dat) {
    $.ajax({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
            xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
            },
        url: "https://docs.google.com/forms/d/e/"+id+"/formResponse",
        data: dat, 
        type: "POST",  
        dataType: "xml",
        xhrFields: {  withCredentials: true },
        statusCode: {
            0:   function() {  console.log("OK") },
            200: function() {  console.log("error") },
            }
        });
    }

A CORS error is being generated, but supposedly, the POST request should still be successful.

Answer №1

If you're looking to tackle this in April 2019

Today, I delved into this task. Here's the latest solution:

Every field in the Google Form is assigned a unique ID. To retrieve it, generate a pre-filled link by filling out all relevant form fields that you want to programmatically submit

Important Note: To ensure the URL can be accessed without restrictions, make sure to disable domain restriction (applies to GSuite paying users)

https://i.sstatic.net/PJ3Hp.png

Afterward, copy the link and paste it into your browser. The URL structure should look like this:

https://docs.google.com/forms/d/e/[FORMID]/formResponse

Each parameter consists of a key/value pair format: entry.XXXXXX=value

The prefilled link will provide the value of XXXXX for each applicable field

The request must include the following headers:

Method: GET

Content-Type: application/x-www-form-urlencoded

The final request should resemble this:

https://docs.google.com/forms/d/e/123332233bsj333/formResponse?entry.123456=value1&entry.2333442=value2&submit=Submit

Don't forget to add submit=Submit at the end of your request!

Answer №2

Despite encountering a CORS error, it is believed that the POST request should still be processed.

Although a successful POST request can be made, experiencing a CORS error and not being able to access the response only applies to Simple Requests.

This happens because your request includes:

  • Custom headers like Access-Control-Allow-Origin and Access-Control-Allow-Methods, which are actually response headers and should not be included in the request
  • Credentials (using withCredentials: true)

... turning it into a Preflighted Request.

Prior to executing the POST request, the browser will first send an OPTIONS request to seek permission.

Since permission is denied, the request fails.


It's important to note that even if you were to convert it to a simple request and successfully make the POST, the status would still be 0. In case of a CORS error, the status cannot be accessed.

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

Transitioning from jQuery to Prototype

After switching from a jQuery background to Prototype, I am curious if there is a chart available that shows the equivalent prototype methods for specific jQuery methods? To be more specific, I am searching for the equivalent of $('#my-id').prep ...

Building a stylish table using Material UI in ReactJS

I've been working on creating a dashboard using the Material UI minimized table. You can check out the documentation here: Material UI Tables However, I've encountered an issue that has me stuck for the past 5 hours. While I was able to successf ...

Convert an array to UTF-8 encoding and extract the values into a text input field

Having encountered a minor issue, I've successfully moved data from one file to another using Ajax with the help of echo in my query. However, I'm now attempting to utilize json_encode(); and facing some difficulties. Could someone please point o ...

When querying a MongoDB object in Node.js, the inner value may sometimes return as undefined

After retrieving a store object from MongoDB, my focus shifted to utilizing the value stored in store.comments. Upon logging the store value, here is what I found: store:{ _id: 57e246f73e63d635cce3d174, __v: 0, comments: 57e246f73e63d635cce3d177, l ...

The jQuery extension for XDomainRequest in the $.ajax function called onprogress is

Summary: I am trying to make this compatible with this: Detailed Explanation: My goal is to develop a jQuery extension that introduces a progress method to the $.ajax object and works seamlessly with IE8 & IE9's XDomainRequest object. Currently, I ...

The MySQL query is returning a blank result with only the column headings displaying

I have been working on improving my skills in PHP and AJAX by developing an application that enables users to search a database for real-time product stock information. Currently, I am facing an issue where the headings are displayed when a user types a le ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack. Currently, I am trying to test a POST API endpoint that is built using express. The node server is up ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Is there a way to dynamically calculate the total of a column when a new row is added using Javascript?

I am new to both javascript and cakephp. I successfully implemented a feature that allows me to add a new row using javascript, but now I am looking to calculate the total sum of the "amount" column whenever I input a value in the amount field. Below is th ...

In what situations might a finally block fail to execute?

Are there any circumstances where the code in a finally block may not be reached, aside from the usual suspects like process exit(), termination signal, or hardware failures? In this TypeScript code snippet that usually runs smoothly in node.js, occasiona ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

What is the best approach to convert text to uppercase or lowercase based on the length of the string in Angular version 1.5?

My goal is to apply text formatting to a string named 'name'. Once the string is entered into an HTML form and the save button is clicked, the new formatted string should be displayed below the form. The formatting rule states that if the length ...

Encountering an error: Module missing after implementing state syntax

My browser console is showing the error message: Uncaught Error: Cannot find module "./components/search_bar" As I dive into learning ReactJS and attempt to create a basic component, this error pops up. It appears after using the state syntax within my ...

How to dynamically assign a value in a React datepicker component in a React application

Having troubles with react-datepicker? I encountered an issue where setting the value of react-datepicker from props caused it to either not show the value or display a 'wrong time format' error. Here is a snippet of the Datepicker code: this.sta ...

What is the best way to send a request every 2 seconds using AngularJS and Node.js?

My Node.js server collects data, and my AngularJS client needs to make an HTTP request to the server every two seconds in order to display updated data. I am concerned about Chrome potentially blocking my requests if they reach a maximum limit. Is there an ...

Sass is throwing an error message saying 'Module not found' during the compilation process

After installing sass using npm ($npm install sass), I attempted to create a JSON script. Unfortunately, when running it, I encountered an error stating 'Cannot find module'. ...