I am searching for python/jquery related answer but I havn't been lucky so far!
I am trying to download csv file sent by a server via AJAX GET call. I am able to download it successfully via blocking-get request but I want to achive the same via ajax.
Python/Django View
header = None
rows = []
for student in students:
if not header:
header = get_header()
rows.append(header)
rows.append([student.id, student.name, student.marks])
buf = StringIO()
writer = csv.writer(buf)
for row in rows:
writer.writerow(row)
response = HttpResponse(buf.getvalue(), content_type='text/csv')
response['Content-Disposition'] = 'attachment'
return response
AJAX GET Request
<script>
$(document).ready(function () {
$('#download-grades').on('click', function (event) {
event.preventDefault();
var grades_csv_url = $(event.target).data().url
$.ajax({
url: grades_csv_url,
type: 'GET',
// dataType: 'text/csv; charset=utf-8',
success: function (response, status, xhr) {
console.log('-')
},
error: function (jqXHR) {
console.log(jqXHR.responseText); // the response is always received in error not in success.
}
});
});
})
</script>
Whats Next?
I want to start downloading the file when the csv response is received.