Skip to content
Advertisement

Workaround to XHR request and download prohibition

I have a weird situation: I get data from a Postgres database, and from that data, I create a table in a website, using Grid.js. Each line has a “Download” button, that takes 2 arguments from that table entry and send them to a function. Originally, that function would make a XHR request to a php file, that gets files from another DB, creates a ZIP file, and should send it to the user, with readfile().

Table

I now discovered that this is not possible. XHR does not allow downloads for safety reasons. I could do something using window.location to call the PHP file, and get the download, but I am dealing with hundreds of files, so I cannot write hundreds of PHP files to get the data individually. I could, but it would be very hard to maintain and manage all those files, and it feels unprofessional.

Right now, I can:

  • Send the data from JS to PHP, using POST;
  • Using those two variables, fetch the data from another Postgres server;
  • Use those files and create a ZIP file (The ZIP files cannot be stored permanently in the server, because of storage restrictions. A cronjob in the server will clean the files eventually)

I need to:

  • Send the ZIP to to the user;
  • Maintain the simplest code possible, in a way that I can feed 2 variables and it just works, without needing a PHP file for each table line (if that makes sense)

The current code is:

  • Javascript
JavaScript
  • PHP
JavaScript

Advertisement

Answer

As pointed out by @epascarello here, a simple GET request solves this.

Even though I was afraid of not using POST because of an SQL injection attack, the variables pass through a pgsql2shp program, and that only accepts a valid schema and table names, so no need to worry about that as much.

I am currently using this KISS code, and it works:

JavaScript

In PHP, it’s only needed a small change from the POST reception to a GET reception. The variables are already separated, no need to decode anything:

JavaScript

This goes to show that sometimes, we look so deep into a problem that the solution is right in front of us.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement