javascript - File is not being downloaded when requested through Ajax using JQuery -
i need download .csv file information website, i'm using link , javascript/jquery table servr , create file.
i have link supposed download file when clicked:
<a class="areasummaryexport" value="1">...</a>
and have in js file:
this adds click listener link:
$('.areasummaryexport').on('click', function(){ exportareasummary($(this).attr('value'), $(this)); });
this function gets table server using ajax request , sends corresponding function process:
function exportareasummary(selected, sender){ $.ajax({ url: 'admin_ajax.php', method: 'get', datatype: 'json', data: {action: 'exportareasummary', area: selected} }).done(function(data){ console.log('done'); exporttabletocsv.apply(sender, [$($(data.table)[0]), data.name, data.header]); }).error(function(xmlhttprequest){ console.log('error'); console.log(xmlhttprequest); }); }
finally function adds href
attribute link information of file download:
function exporttabletocsv($table, filename, header) { console.log('printing'); var $rows = $table.find('tr:has(td),tr:has(th)'), // temporary delimiter characters unlikely typed keyboard // avoid accidentally splitting actual contents tmpcoldelim = string.fromcharcode(11), // vertical tab character tmprowdelim = string.fromcharcode(0), // null character // actual delimiter characters csv format coldelim = '","', rowdelim = '"\r\n"', // grab text table csv formatted string csv = '"' + 'sep=,' + rowdelim + (header? header.join(coldelim) + rowdelim : '') + $rows.map(function (i, row) { var $row = $(row), $cols = $row.find('td, th'); return $cols.map(function (j, col) { var $col = $(col), text = $col.text(); return text.replace(/"/g, '""'); // escape double quotes }).get().join(tmpcoldelim); }).get().join(tmprowdelim) .split(tmprowdelim).join(rowdelim) .split(tmpcoldelim).join(coldelim) + '"', // data uri csvdata = 'data:application/csv;charset=utf-8,' + encodeuricomponent(csv); $(this) .attr({ 'download': filename, 'href': csvdata, 'target': '_blank' }); console.log('printed'); }
the problem gets info csv file , adds in href
attribute in link, won't download file (i have click again work).
i know last function works because use somewhere else, there have table on screen there's no ajax involved. i'm guessing problem ajax, not sure where.
i tried firing click event through js doesn't work either.
i recommend create csv @ server side php program , set content-type "application/vnd.ms-excel" (or) "text/csv" , set "content-disposition: attachment; [yourfilename] "
refer create csv file user in php
refer force download csv file
simply put hyperlink as
<a class="areasummaryexport" href="admin_ajax.php" value="1">...</a>
Comments
Post a Comment