Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to output file to browser after jquery ajax call

I have a link on the website to a php file that generates native excel file on a fly ant outputs it directly to browser via headers for user to to open/save. Since it takes some time for the file to be generated I'd like to use jQuery Ajax to make the call and use some loading animation in the mean while.

The only thing I'm not sure how to do is how to output the file into the browser after Ajax call? Is it even possible?

like image 478
Caballero Avatar asked Oct 11 '22 00:10

Caballero


1 Answers

(N.B. This is a paraphrasing of @dmitry's answer, but just elaborated upon)

The problem you have is that there is no means of directly returning a file to the user via AJAX - the browser has to request the file using a normal, synchronous HTTP request.

To solve this, your PHP will need to:

  1. Generate the Excel file as normal.
  2. Instead of writing the file back to the user, save it somewhere on the server's filesystem (i.e. using file_put_contents() or similar).
  3. Return the file path to the user.

Your JS, on receiving this response will then need to:

  1. Read the Excel file path back from the PHP script.
  2. Open the Excel file in a new tab/window using window.open() (or redirect in the current tab/window by setting location.href).
like image 135
Jim O'Brien Avatar answered Oct 14 '22 03:10

Jim O'Brien