1

I'm using ajax to POST, but AJAX won't trigger the file download.

I need to POST without using forms, because I'm using values from many elements on page, so I made a javascript function to get those values and create an array then POST to the php target file.

How can I POST these values and trigger the download the file, without using form submit, but collecting the elements values and sending it to the target php page?


Javascript parses content and creates an array of values, and post to PHP:

['Jordan','22','Male','Other Info']

PHP file uses that array to insert these values into a DOCX (document), then returns the download URL, note that the file isn't kept in the server.

Here's the ajax POST answer:

Access-Control-Allow-Origin:*
Cache-Control:max-age=0, no-cache, no-store, must-revalidate
Connection:Keep-Alive
Content-Description:File Transfer
Content-Disposition:attachment; filename="modelos/calculos/tempo_contribuicao_2014-11-12.docx"
Content-Length:18943
Content-Transfer-Encoding:binary
Content-Type:application/vnd.openxmlformats-officedocument.wordprocessingml.document
Date:Wed, 12 Nov 2014 15:57:39 GMT
Expires:Wed, 11 Jan 1984 05:00:00 GMT
Keep-Alive:timeout=15, max=98
Pragma:no-cache
Server:Apache/2.0.63 (FreeBSD) PHP/5.2.6 with Suhosin-Patch
Vary:User-Agent
X-Powered-By:PHP/5.2.6
BernardoLima
  • 1,103
  • 2
  • 16
  • 35

1 Answers1

1

You can achieve the same using:

Step 1: First, send Ajax request to post parameters to server

Step 2: Generate file on server using PHP & return the filename

Step 3: In ajax success callback, just use location.href='<PATH_TO_PHP_TO_DOWNLOAD_FILE>?filename=fname' //<-- fname is filename returned in ajax success callback

Step 4: Another PHP file will download that file for you & will remove that after sending that on browser.

Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
  • No way to achieve that without saving the file on the server? Not even with only PHP without using form submit? – BernardoLima Nov 12 '14 at 15:42
  • I am not sure but if you follow these steps, you are removing file after download. – Apul Gupta Nov 12 '14 at 15:43
  • 1
    @BernardoLima you just need a link to the php file which will output whatever the file it is. with correct header and mime, you can force download after clicking the link. – itachi Nov 12 '14 at 15:49
  • @BernardoLima, I agree with @itachi. But, `location.href` will not redirect you if you are using correct mime type & headers. It's up to you how you want to show this to user. – Apul Gupta Nov 12 '14 at 15:54
  • @BernardoLima in the page which will download the file. As there are 2 PHP involved. one is to generate file & another is to download that. You need to use headers/mime in second one. – Apul Gupta Nov 12 '14 at 15:55
  • Ok I'm going to try that. – BernardoLima Nov 12 '14 at 15:55