Tuesday, December 14, 2010

dynamically loading Google Chart Image in an iFrame using POST request and Javascript (prototype)

Google Chart API online document gives a good example on how to write html code to load a Google Chart using POST request, you can find it here.  The benefit of this method is the higher limit of data size that can be posted (16kB instead of 2K in the URL).

Here I want to post an example to show how this post request can be generated from within a dynamically generated iframe. This would be useful for showing a chart using dynamic data which, say, are downloaded from another page using ajax request (prototype library is used).


This is how the DOM document might look like:
<div id="outerdiv" width="700" height="400">
</div>

and the javascript code:

var fstr =
     "<iframe src='' id='gchart_frame' width='710' height='410'></iframe>" ;
var formstr = "<form id='gchart_form'" + 
   " action='http://chart.apis.google.com/chart?chid=" + 
   Math.random() + "' method='POST'>" ; 
// random chid to prevent browser caching
formstr += "<input type='hidden' name='cht' value='lc'/>" ;
formstr += "<input type='hidden' name='chs' value='700x400'/>" ;
formstr += "<input type='hidden' name='chd' value='t:0,1,2,3,5,123" ;  
  // put your data here, can be dynamically downloaded from an ajax source.
formstr +="<input type='hidden' name='chxt' value='x,y'/>" ;
formstr +="<input type=\"submit\"/></form>" ;

$('outerdiv').innerHTML = fstr ; 
  //  embed the iframe ($) is from prototype library

var ff = $('gchart_frame') ;
if (! Prototype.Browser.IE) { // for other browsers
  var y=(ff.contentWindow || ff.contentDocument);
  if (y.document)
       y=y.document;
  y.body.innerHTML = formstr;
  y.forms[0].submit() ;  // load the chart within the iframe
}
else { // IE
   var ffs = document.frames["gchart_frame"] ;
   var divn = ffs.document.createElement('div') ;
   divn.innerHTML = formstr;
  ffs.document.appendChild(divn) ;
            
   var gchartform = ffs.document.getElementById('gchart_form') ;
  gchartform.submit() ;
}

Monday, December 6, 2010

How to get current time with milliseconds using Linux shell script

This is something I believe would be useful for many people when you want to, say, log data using linux shell script, or something alike.

The linux "date" command does have a parameter that gives current time in nanosecond accuracy, but not millisecond.  So what you want to do is to extract a substring from "date" output to convert the value into milliseconds.

filename="/tmp/tmpfile.log"

nanos=`date +%F-%T.%N`
echo -n "${nanos:0:23}" > $filename


Code above generates a timestamp in %Y-%m-%d-%H:%M:%S.mmm format and write into a file named /tmp/tmpfile.log.

${nanos:0:23} extracts the first 23 characters from the string generated by shell command "date +%F-%T.%N", where the parameter "%N" generates zero-filled nano-seconds of current time.