Skip to content Skip to sidebar Skip to footer

Converting An Html Table To Json To Pass To An Ajax Call For Downloading As A Csv

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 jus

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Converting An Html Table To Json To Pass To An Ajax Call For Downloading As A Csv"