0

Is there a way I can send back json to my ajax call as well as have the client download a file when the response is sent?

I tried passing a simple code set:

res.setHeader('Content-disposition', 'attachment; filename=theDocument.txt');
res.setHeader('Content-type', 'text/plain');
res.charset = 'UTF-8';
res.write("Hello, world");

but that did not create a downloadable file for the client.

I also tried to send back the JSON data with the headers tweaked to also pass back a file but I had no luck.

Tamer
  • 1,724
  • 4
  • 16
  • 15
Matthew Wong
  • 274
  • 1
  • 7
  • How about sending back a json response which contains your data, as well as a link to the downloadable file. You can than make an additional call to download the file. – levi Feb 27 '14 at 20:14
  • See here - http://stackoverflow.com/questions/6668776/download-file-through-an-ajax-call-php – levi Feb 27 '14 at 20:14
  • I would but the file isn't static. Nor do I want to create one. I basically want to put some sting data in a text file thats dynamically created and sent through some bytes. Thanks for your suggestions though – Matthew Wong Feb 27 '14 at 21:29

1 Answers1

1

The code that you have provided in your question, if it works, is only going to start a download for the end user. It will not return an AJAX response to your web application.

Since your requirement is to both a.) initiate a file download and b.) receive an AJAX response in your application, I think the solution I have used will suit your needs. I can't think of any other way that this can be done, unless you want to make more than a single HTTP request.

Basically, we send the data back from the server as a normal AJAX request. Then, in the browser, we initiate a file download.

Here is an example:

api.request("/ajax/data", function(err, data) {
  # Once you get your data back from the API, we make the browser download it.
  var toDownload = encodeURIComponent(data);
  var a = document.createElement('a');
  a.href = "data:text/php;charset=UTF-8," + toDownload;
  a.target = '_blank';
  a.download = 'my_downlaoded_filename.txt';
  document.body.appendChild(a);
  a.click()
});

Please give it a shot and let me know if it works. I translated that from CoffeeScript, so hopefully I didn't add in any typos. ;)

EDIT: I tried your code in Node.js and it did initiate a file download. But, still, it sounds like your requirement encompassed more than just initiating the download.

Jonathan
  • 5,495
  • 4
  • 38
  • 53