Including hidden data in an HTML page for javascript to process

derekcohen picture derekcohen · Jan 20, 2011 · Viewed 32.5k times · Source

I produce a complex HTML summary report from data in a database which could be a summary of maybe 200,000 rows in the database. The user can click a link to request an Excel version.

When they do a JS script extracts the key components of the report and stuffs them into a form in a hidden iframe. This form submits to a server-side script which generates the Excel version of the report (without the graphics etc).

As the calculations for the report are complex and "costly" it makes sense not to run them again to create the Excel version as all the data is on the page already. Also the user may have customised the report once it is loaded and I can use JS to pass those preferences to the form as well so the Excel doc reflects them too.

The way I am doing this is to include the following for each component of the report that transfers to a row in the Excel version. I've hijacked an HTML tag that isn't otherwise used.

   <code id="xl_row_211865_2_x" class="rowlabel">Musicals}{40%}{28.6%}{6</code>

The code element above is a summary of the row below in the HTML report which becomes one row in the Excel doc and includes the label and various data elements. There may be a thousand or more such elements in one report.

alt text

As the data contains text I've had to use something like }{ as a field separator as this is unlikely to occur in any real text in the report. I have code set to display:none in the CSS.

When the user wants an Excel version of their report the JS code searches the HTML for any <code> elements and puts their className and innerHTML in the form. The className indicates how to format the row in Excel and the data is then put into adjacent cells on the Excel row.

alt text

The HTML report shows one percentage base (they can toggle between them) but the user preference when requesting an Excel version was to include both.

Is there a better way of doing this?

(As this is a part of a complex web app no user is going to turn CSS off or lack javascript or they wouldn't get this far) ADDED: I can't use HTML5 as the users are corporates often on older browsers like IE6

Answer

David M&#229;rtensson picture David Mårtensson · Jan 20, 2011

Use the new data- attributes

http://www.javascriptkit.com/dhtmltutors/customattributes.shtml

<div data-row="[[&quot;Musicals&quot;,40,28.6,6], ...]">

The div could be the TD tag or TR tag or any other relevant tag already related to the row and the &quot; is the escaped ".

That makes the data hidden from view and also ensures that there will come standard solutions to process the data.

Also for encoding data I would suggest using JSON as that is also a standard that is easy to use.