Force loading after ajax call

I have a php script that is waiting for ajax calls in

www.mydomain.com/file.php

The ajax call contains some variables that the .php file will use to generate some csv results,

Is it possible that the user can download the csv content created by file.php without having to save it somewhere on the server and more?

I don’t want to redirect the user to any other page, I want them to click a button, then view the download dialog and let them download the csv file.

+1
source share
3 answers

Putting elements into the form and sending them just seems to be hacked, and I don’t feel comfortable using it.

When you use these types of things, I think you take a little risk, the next versions of browsers may simply not support them.

In addition, I pass complex arrays as parameters in my ajax call to the server, and it is not easy to convert them all to an html form if I do not serialize the arrays in the hidden element and unesterialize it on the server side, but that is all too complicated.

What I did was when the ajax call was made, the server saves the output in the session, then it returns a unique key for this value, another page on the server will simply echo when this key is indicated to it as input,

Thus, the user clicks on something, then an ajax call is made, then the server saves it in the session, then the user clicks the download link, and then the server deletes this session.

This may not be the most perfect solution on purpose, since the user needs to double-click, but it seems more standard to me.

+2
source

Of course, in the PHP file, before you output anything, set the content type to something that the browser will load:

header("Content-Type: application/octet-stream"); 

Also, it is good practice to include too (and allows you to suggest a file name):

 header("Content-Disposition: attachment; filename=somefile.csv;"); 

Depending on the browser, sometimes only a later version is required, but I usually use both to make sure.

+3
source

@ user893730- Why are the elements placed on the form and represent them "hacked"? In addition, I don’t understand why serialization and deserialization of array data is “complicated” - there are a billion libraries that support just such things.

+1
source

Source: https://habr.com/ru/post/917695/


All Articles