1

I would like to make AJAX request to GET some data from a server. I would then like to prompt the client to save this data on his/her computer so it can later be accessed outside the browser session. Is this saving functionality possible with JavaScript or would I be required to use a Flash library? Could I do this locally by using a URI? Could I use HTML5's local storage?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
  • you need [this](http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp) and [this](http://stackoverflow.com/questions/7717851/save-file-javascript-with-file-name) and maybe [this](http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side) – dudeofea Mar 02 '13 at 20:24
  • Your last [this](http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side) was helpful –  Mar 02 '13 at 20:39

1 Answers1

0

Once the data is on the client side, there is no way for Javascript to save it locally without a plugin like Flash. HTML5 has the download attribute, which solves all this, but it has little support [2013-03-02].

Instead, what you can do is build the data on the client and then save the data on the server as a file to be downloaded directly as an attachment. You'll need to use the HTTP Header Content-Disposition to do this.

Here's an example in PHP.

Demo: jsFiddle

Server:

<?php
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename=data');

echo $_POST['data'];?>

Client:

<!-- language: lang-html -->

<form action="http://thinkingstiff.com/stackoverflow/download.php" method="POST">
    Data to save: <input name="data" type="text" />
    <button>download</button>
</form>
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
  • I want to have several discrete datasets hosted on the server. The client can request one of more of these datasets to be combined clients-side and then saved. I don't want to save the infinite set of permutations on the server, nor do I want the server to do the computation heavy combination operations on the datasets. Nice suggestion for normal file download though –  Mar 02 '13 at 20:43
  • @0xDEADFEED Ah, your question said "get data from server". Instead, combine on the client and send back to the server using AJAX to be saved and immediately downloaded. This is how many online word processors and image editors work. – ThinkingStiff Mar 02 '13 at 20:45
  • @0xDEADFEED I change the code to do the same thing with client data dynamically. – ThinkingStiff Mar 02 '13 at 20:57
  • Sounds unnecessarily bandwidth intensive, considering the data was already in the client's RAM but I digress... –  Mar 02 '13 at 21:00
  • @0xDEADFEED Yeah. Without Flash it's ugly. HTML5 has the `download` attribute to solve all this, but it has no support yet. – ThinkingStiff Mar 02 '13 at 21:04
  • I could force my users to use Chrome which supports `download`, but I don't think they would appreciate that... –  Mar 02 '13 at 21:12