DEV Community

Discussion on: Introduction to XMLHttpRequest (XHR)

Collapse
 
lawrencejohnson profile image
Lawrence • Edited

One correction or at least clarification to consider is that you can't download (in a common nomenclature sense) a file with XHR. That is to say you have no way of saving it locally like most users might assume when they think of downloading. You can retrieve a file's contents which is technically downloading, but you can only do things with it within your app. There's no way to offer the user a save dialog, nor can you save to a user's hard drive through JavaScript alone.

The other side-note is that your javascript syntax is not very backwards compatible. Your jQuery example solves that problem, but users on IE are going to have parse errors with your vanilla code that could stop all javascript on the page once that code is encountered.

Collapse
 
mcgurkadam profile image
Adam McGurk

So that’s not exactly true on the file downloading....you can still stream file contents back to the local machine, create an object url, set it as the href on a created a tag, append it to the body, fire the “click” method on the element, and then remove the element from the DOM. It will bring up the OS’s download dialog as if you hit a “download” button.

Collapse
 
lawrencejohnson profile image
Lawrence

I suppose if you needed a temporary or auto-generated file to have immediate expiration on the server that would be a very creative way of getting around returning a download URL that I hadn't thought of.

Thread Thread
 
mcgurkadam profile image
Adam McGurk • Edited

That's fair. The only reason I responded quick is because on our platform that's how we make downloadable CSVs available - ie we take a JSON response from the server, parse it back into CSV and then do what I said above

Thread Thread
 
lawrencejohnson profile image
Lawrence • Edited

Yeah, we do a lot of similar work, but we use either a download handler or a temporary file system with expiration policy to generate the download (csv/pdf/etc) server-side. We do have one app that that could benefit from your approach though where we parse a user-provided CSV in javascript, let them manipulate, but then we are pushing that data to the server for file generation to retrieve the modified version of their original CSV data. I'll be considering a rework on that since there's literally no reason for it to ever go to the server if we use your approach.

Collapse
 
attacomsian profile image
Atta • Edited

Thank you for the feedback.

Although XHR does not trigger file download, you can still use it to download files. Here is an example I found on the internet.

For backward compatibility, I believe, JavaScript is much more evolved in recent years. We should follow the best modern practices and learn to live without IE. There is a whole new universe beyond IE.