FtDRbwLXw6
FtDRbwLXw6

Reputation: 28891

Force download via AJAX

I'm looking for a way to POST data to a backend script, use it to generate a temporary file on the fly (temporary in that it's dynamically generated and not saved to disk on the server), and then offer it to the client as a download.

I have the backend script functioning fine. The problem is that I haven't yet found a way to get the download prompt via an AJAX call.

If I weren't POSTing data, I would just use something like:

window.location.href = 'path/to/my/script.php';

Is what I'm after even possible? Can it be done without resorting to "hacks" like dynamically injecting a form into the DOM and submitting it, or opening up another browser window, etc.?

Upvotes: 1

Views: 818

Answers (2)

moonwave99
moonwave99

Reputation: 22817

  1. make POST request;
  2. create the resource;
  3. answer with the resource path;
  4. window.location.href = resourcePath.
  5. [optional] want to secure such resource from third part download? Attach a CSRF token, and make the resource available only if CSRF check is passed - otherwise congratulations, you just won a 403 puppy!

If the resource has proper headers, the browser will ask you to save / open it with specific app. / an so.

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318488

You can't do that without a classic form submit unless you can somehow make the download available via GET.

However, doing that would be a good idea anyway since download managers etc. often don't work well with POST - so simply make your script generate a temporary URL and then redirect to that URL using the JavaScript you already posted in your question.

Upvotes: 1

Related Questions