Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Create a new Google Docs Spreadsheet from content using AJAX


This example shows how one could use jQuery to make an AJAX request that creates new Google Docs Spreadsheet from existing text/csv content. This particular examples uses ClientLogin
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"
        type="text/javascript"></script>

<script type="text/javascript">
var token = 'YOUR_CLIENTLOGIN_AUTH_TOKEN';

function constructContentBody(docTitle, docType, contentBody, contentType) {
  var atom = ["<?xml version='1.0' encoding='UTF-8'?>",
              '<entry xmlns="http://www.w3.org/2005/Atom">',
              '<category scheme="http://schemas.google.com/g/2005#kind"',
              ' term="http://schemas.google.com/docs/2007#', docType, '"/>',
              '<title>', docTitle, '</title>',
              '</entry>'].join('');
             
  var body = ['--END_OF_PART\r\n',
              'Content-Type: application/atom+xml;\r\n\r\n',
              atom, '\r\n',
              '--END_OF_PART\r\n',
              'Content-Type: ', contentType, '\r\n\r\n',
              contentBody, '\r\n',
              '--END_OF_PART--\r\n'].join('');
  return body;
}

function createSpreadsheetFromContent(title, content, contentType) {
  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

  $.ajax({
    type: 'POST',
    url: 'http://docs.google.com/feeds/documents/private/full',
    contentType: 'multipart/related; boundary=END_OF_PART',
    data: constructContentBody(title, 'spreadsheet', content, contentType),
    dataType: 'xml',
    beforeSend: function(xhr) {
      $('#data').html('uploading...');
      xhr.setRequestHeader('Authorization', 'GoogleLogin auth=' + token);
    },
    success: function(resp) {
      $('#data').html('Spreadsheet created!');
    }
  });
}
</script>
</head>
<body>

<div id="data"></div>

<button onclick="createSpreadsheetFromContent('ANewTitle', '1,2,3,4', 'text/csv')">Create spreadsheet w/ content</button>
</body>
</html>