Reputation: 356
I'm posting my form data to a google spreadsheet (it's working, I just can't get a response back) and am trying to return the values that were sent. The spreadsheet has 3 headers - name, image, result. Whenever I send the form data, I can write the values to the spreadsheet under the correct headers, I just can't get a responseText or statusText or anything like that back. How would I go about returning and console.logging the values?
[index.js]
var form = document.createElement('form'),
node = document.createElement('input');
form.method = 'POST';
form.action = 'google apps script url';
form.style.display = 'none';
var params = {'name': name, 'image': image, 'result': result};
for (key in params)
{
node.name = key;
node.value = params[key];
form.appendChild(node.cloneNode());
}
document.getElementById('formContainer').appendChild(form);
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send('name=' + name + '&image=' + image + '&result=' + result);
console.log(xhr.responseText); //returns blank...same w/ status / statusText / etc
document.getElementById('formContainer').removeChild(form);
[google apps script]
function doPost(e)
{
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow() + 1;
var row = [];
for (i in headers)
{
row.push(e.parameter[headers[i]]);
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow, 'values': e.parameter}))
.setMimeType(ContentService.MimeType.JSON);
}
Upvotes: 2
Views: 4390
Reputation: 5892
You are making an asynchronous request by setting the async parameter as true xhr.open(form.method, form.action, true);
. This means the code doesn't wait for a response from the webpage and proceeds to next line thus has an empty xhr.responseText
You will have to use the XMLHttpRequest.onload()
function to define the callback function. This will be executed when the response from the web application is received, like so
xhr.onload = function() {
console.log(xhr.responseText);
};
Your code would look like this :
xhr.open(method, action, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send('name=' + name + '&image=' + image + '&result=' + result);
More details on asynchronous and synchronous can be found here.
Note: Synchronous calls have been deprecated for latest versions of Mozilla and Chrome. So it is advisable not to use them.
Upvotes: 4