0

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.

A.J.
  • 8,557
  • 11
  • 61
  • 89
  • Quick fix...create a hidden `a` element...on `$('#download-grades').on('click'` set the `href` attribute to your `grades_csv_url`...then trigger a click on that hidden `a` element....also read this https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – Hackerman May 25 '18 at 18:00

2 Answers2

1

Have you tried setting this in your javascript instead of creating a ajax?

document.location = grades_csv_url

1

you can convert text response to csv in js:

var element = document.createElement('a');
element.href = 'data:text/csv;charset=utf-8,' + encodeURI(response);
element.target = '_blank';
element.download = 'csv_data.csv';
element.click();