0

In my Grails application, a user can click on a g:link which will call my controller to export certain data to a CSV file. This works with no problems.

I then moved that button to a jQuery dialog box and, when the button is clicked, I use

${remoteFunction(action:'export', onSuccess:'closeMe();', id:courseInstance?.id)}

to call the same controller method and close the dialog box. I've confirmed that the method is actually called, and the dialog box closes. The user is not prompted with the CSV dowmload, however. I'm assuming this has something to do with the remoteFunction, but I'm not really sure. Can anyone explain why this might happen, and a potential fix?

Thanks!

littleK
  • 19,521
  • 30
  • 128
  • 188

1 Answers1

1

With AJAX requests you can't handle to download content as attachment and so it can't trigger the Save As dialog.

There are a couple of workarounds for this:

  • Use a plain g:link as before and bind the 'closeMe();' function to the 'click' event. The problem is that you have no control on error or success response.
  • Use an iframe: You can create a temporary invisible iframe and set its location to the URL of the file to download. It also has the backside of not controlling the success/error response.

The code could be the same as in this answer:

<script type="text/javascript">
function downloadURL(url) {
    var iframe;
    var hiddenIFrameID = 'hiddenDownloader';
    iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');  
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;   
}
</script>

And the link

<a href="javascript:downloadURL(${createLink(action:'export')})">Export</a>
Community
  • 1
  • 1
chozero
  • 411
  • 6
  • 12