How does jQuery.post () work with Content-Disposition: attachment?

Here is a little crazy. I am making an Ajax call using jQuery.post as follows:

$.post('php/print.php',{data:dS},function(res){... },"text"); 

I am returning from print.php (as a test):

 header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=test.doc"); echo "<html>"; echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">"; echo "<body>"; echo "Testing-2-3!"; echo "</body>"; echo "</html>"; 

Data goes through a penalty according to Firebug, including headers. But how do I get a browser (Firefox in this case) to prompt the user to save the attachment?

Thanks.

+1
source share
2 answers

It is simply not possible. AJAX requests never invoke user prompts.

However, you can simply return the request, for example. JSON or plaintext containing the url and then use location.href = ...; to redirect to it; this will result in the query you are looking for.

If the request always leads to a file download, you can also consider using a regular form and not using AJAX at all; if the answer starts the download dialog, the previous page will still remain in the browser window.

+5
source

Why don't you refer directly to print.php

and output php output to browser using this code

 $fp = fopen("php://output", 'w'); header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=test.doc"); $fp = fopen("php://output", 'w'); fwrite($fp,"your content here"); fclose($fp); 
-1
source

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


All Articles