Reputation: 707
I am having to write a reporting system in ASP classic. The people who wrote the wireframe have no concept of performance/speed/how SQL works and so forth so I have lots of fun just getting the data out of the DB.
However they want to have buttons the users can press to "download" the report to a CSV file.
I could submit the form and re-run the SQL (which takes a long time due to the number of reports shown on one page and their format) - and then just send it to the browser as a file.
OR I was thinking of using JS or jQuery etc to take the desired table of contents, somehow convert that to a JSON object, post that to another page using AJAX and then in that other page take the JSON and decode it into a CSV format which can then be delivered to the user as a file.
I just think this JS approach would be quicker and also if I could make it generic so it could take any table with a class on it e.g "report" and convert that into a JSON object that would be used to create a CSV I could easily re-use this code on the hundreds of reports they have made me write.
Does anyone have an JavsaScript code or jQuery that would take a table in any format (it has a thead with column headers, the a tbody with the main contents) and encode it to a JSON or JS object for posting to another page where I could then de-encode it and pipe it out as a CSV file?
Here is a screen shot of one of their reports,
Upvotes: 0
Views: 982
Reputation: 15351
A possible solution to the problem could be to already generate the CSV formatted version of the data for each report when the page that displays the given report is requested. (Database is only queried once per report.) Send the data back in the response in the expected format to display it in the table and save the CSV file to a temporary location on the server.
This way you can place a link near the table 'download CSV' which will point to the already existing file. It will avoid having to query the same data twice for one report OR to having to send the same data to a roundtrip between server and client.
Upvotes: 0
Reputation: 3188
Javascript doesn't provide a way to save text to a file, so you would still have to do that server-side, i.e. by AJAX as you already suggested.
With jQuery you could do something like this (not tested), and send it via an AJAX request.
var headers = [];
$('table.report thead > tr > th').each(function($i, obj) { //or <td> instead of <th>
headers.push($(obj).text());
});
var data = [];
$('table.report tbody > tr').each(function($i, tr) {
var row = [];
$(tr).find('th').each(function($h, td) {
row[headers[$h]] = td.text();
});
data.push(row);
});
var json = JSON.stringify(data);
However I don't think this is the preferable way, because it's still user-input. I could put some random data in a POST and get a CSV in return.
A better way would be to cache your data you already have, and create a CSV file from the cached data when requested.
Upvotes: 0