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.