Showing posts with label javascript. Show all posts
Showing posts with label javascript. 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>

Using the JavaScript Client Library w/ non-supported Services


The JavaScript client library has helper methods for Calendar, Contacts, Blogger, and Google Finance. However, you can use it with just about any Google Data API to access authenticated/private feeds. This example uses the DocList API.
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('gdata', '1.x');
google.setOnLoadCallback(initialize);

function initialize() {
  var scope = 'http://docs.google.com/feeds/';
  if (google.accounts.user.checkLogin(scope)) {   
    var service = new google.gdata.client.GoogleService('writely', 'DocList-App-v1.0'); 
    service.getFeed(scope + 'documents/private/full/', handleFeed, handleError);
  } else {
    var token = google.accounts.user.login(scope); // can ignore returned token
  }
};

var handleFeed = function(response) {
  var entries = response.feed.entry;
  if (!entries.length) {
    alert('You have no entries!');
    return;
  }
  var html = [];
  for (var i = 0, entry; entry = entries[i]; i++) {
    var title = entry.title.$t;
    html.push('<li>' + title + '</li>');
  }
  document.getElementById('data').innerHTML = html.join('');
};

var handleError = function(e) {
  alert('Error: ' + e.cause ? e.cause.statusText : e.message);
};
</script>

<div id="data"><!-- dynamically filled --></div>

Inject parameters into a string


/* 
 * Formats a string with the given parameters. The string to format must have
 * placeholders that correspond to the index of the arguments passed and surrounded 
 * by curly braces (e.g. 'Some {0} string {1}').
 *
 * @param {string} var_args The string to be formatted should be the first 
 *     argument followed by the variables to inject into the string
 * @return {string} The string with the specified parameters injected
 */
format = function(var_args){
    var args = Array.prototype.slice.call(arguments, 1);
    return var_args.replace(/\{(\d+)\}/g, function(m, i){
        return args[i];
    });
};

format("Is it {0}->{1} or {1}->{0}?", "chicken", "egg") == "Is it chicken->egg or egg->chicken?"

JSON-in-script loader



/**
 * Loads an external javascript source by creating a <script> tag
 * and injecting it into the DOM.
 * @param {string} src Url of the js source 
 * @param {string} opt_id An optional id for the <script> tag
 */ 
function load(src, opt_id) {
  var scripts = document.getElementsByTagName('script');
  
  // prevent from loading same script twice
  var alreadyLoaded = false;
  for (var i = 0, script; script = scripts[i]; i++) {
    if (script.src == src) {
      alreadyLoaded = true;
      break;
    }
  }
  
  if (!alreadyLoaded) {
    var scriptElement = document.createElement('script');
    if (opt_id) {
      scriptElement.setAttribute('id', opt_id);
    }
    scriptElement.setAttribute('type', 'text/javascript');
    scriptElement.setAttribute('src', src);
    document.documentElement.firstChild.appendChild(scriptElement);
  }
};