Search code examples
jqueryajaxgrailsdownload

Download file from Ajax (sort of)


I have this ajax call in my GSP:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: data,
    success: function() {
        alert("Success");
    }
});

This is code block from my controller action:

response.setHeader("Content-disposition", "attachment; filename=sample.csv")
response.contentType = "application/vnd.ms-excel"

def outs = response.outputStream
def cols = [:]

tickets.each() {
    outs << it.ticketNo + ";" + it.subject
    outs << "\n"
}

outs.flush()
outs.close()

I get tickets list from data that I pass from view via $.Ajax method. Than I format that data as CSV and than I want to export that data as CSV file but nothing happens. The data is send to client but there is no file for download as content-disposition is not well formed. What am I missing? I've tried to do something like:

$.ajax({
    url: '${request.contextPath + '/Ticket/passAll'}',
    type: 'POST',
    data: aoData,
    dataType: 'text',
    success: function(result) {
        var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
        window.open(uri, 'tiketi.csv');
    }
});

and in controller I generate plain string, but that way I get a file without extension which is unacceptable.

How can I achieve this? Thank you.


Solution

  • You dont need to do it via ajax. The page will not redirect for file downloads.