Akshay
Akshay

Reputation: 181

How do i save the html form data into google spreadsheet using Google Scripts?

I want to create a HTML,CSS form(like a Google Form) through which i want to accept text data as well as files(like images and documents). I am using Google Script. Here is the form.html file

<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/addons.css">

<form id="myForm">
<input type="text" name="myName" placeholder="Your name..">
<input type="file" name="myFile">
<input type="submit" value="Upload File" 
       onclick="this.value='Uploading..';
                google.script.run.withSuccessHandler(fileUploaded)
                .uploadFiles(this.parentNode);
                return false;
                google.script.run.withSuccessHandler(fileUploaded)
                .doPost(this.parentNode);">
</form>

<div id="output"></div>

<script>
function fileUploaded(status) {
    document.getElementById('myForm').style.display = 'none';
    document.getElementById('output').innerHTML = status;
}
</script>

<style>
input { display:block; margin: 20px; }
</style>

and server.gs

function doGet(e)
{
  return HtmlService.createHtmlOutputFromFile('form.html');
}
var url;

function uploadFiles(form) 
{
  try {

    var dropbox = "Student Files";
    var folder, folders = DriveApp.getFoldersByName(dropbox);

    if (folders.hasNext()) 
    {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }

    var blob = form.myFile;    
    var file = folder.createFile(blob);    
    file.setDescription("Uploaded by " + form.myName);
    url=file.getUrl();
    return "File uploaded successfully " + file.getUrl(); 
  } 
  catch (error) 
  {  
    return error.toString();
  }
}
function doPost(form) { // change to doPost(e) if you are recieving POST data
  var name = form.myName;
  var message = 'Ram';
  var submissioSSKey = 'ID';
  var sheet = SpreadsheetApp.openById(submissioSSKey).getActiveSheet();
  var lastRow = sheet.getLastRow();
  var targetRange = sheet.getRange(lastRow+1, 1, 1, 2).setValues([[name,url]]);
}

The uploaded file is getting stored in my Google Drive but the Text Data is not getting stored in the Spreadsheet

Upvotes: 2

Views: 4235

Answers (2)

Ted Benson
Ted Benson

Reputation: 798

You can also use Cloudstitch's Magic Form utility, which creates a special URL for your spreadsheet that you can just send ordinary POST requests to (or via Ajax). That way you don't have to worry about all the client-side APIs.

http://www.cloudstitch.com/project-templates/magic-form

Upvotes: 1

Kriggs
Kriggs

Reputation: 3778

Remove return false;. You're not executing the doPost...

Upvotes: 0

Related Questions