Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return attachment with $.ajax call

I have an iframe on my page, and inside that iframe I execute code:

$.ajax({
    url: '/SamplePage/ExportToExcel',
    async: false,
    data: par,
    type: 'POST'
});

Response is returned fine, however I don't get 'SAVE ATTACHMENT' dialog, nothing happens... To make things clear, headers are fine (content disposition, mime type etc,), as when I execute that export using plain form submission it works. It seems that it has something to do with ajax call. Will it work somehow?

Thanks

like image 854
dragonfly Avatar asked Dec 29 '10 09:12

dragonfly


2 Answers

To extend Darin's answer, here's how I did it:

I have a hidden form, with a hidden input element to be used to dynamically hold the values I wish to convert/export:

<form id="svg_export_form" method="POST" style="display:none;visibility:hidden">
    <input type="hidden" name="svg" />
</form>

Then I have this jQuery code to dynamically populate the elements with the post parameters, and then submit the form.

$('#svg_export_form > input[name=svg]').val(svg_code);
$('#svg_export_form').attr('action','api/reports/convert/svg/to/png');
$('#svg_export_form').submit();

And because the returned response (fro the api call) has a Content Disposition header set, this form submit action wont navigate the user away from the current page (but just returns the attachment) like a normal form submit, and thus still keeps the illusion of a typical Ajax submit :-)

like image 146
JWL Avatar answered Sep 30 '22 19:09

JWL


You won't get the Save As dialog when using AJAX. If you want to get this dialog simply provide a normal link to the download file:

<a href="/SamplePage/ExportToExcel">download</a>

or if you need a POST request:

<form action="/SamplePage/ExportToExcel" method="post">
    <input type="submit" value="download" />
</form>

When you use AJAX to download a file the contents of this file is retrieved at the success callback but there's not much you can do with it: you cannot save it to the client computer and you cannot get Save As dialog.

like image 28
Darin Dimitrov Avatar answered Sep 30 '22 20:09

Darin Dimitrov