How does jQuery.post() deal with Content-Disposition: attachment?
Asked Answered
S

2

1

Going slightly crazy here. I'm making an Ajax call using jQuery.post as follows:

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

I'm 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>";

The data is coming through fine according to Firebug, including the headers. But how do I get the browser (Firefox, in this instance) to prompt the user to save an attachment?

Thanks.

Sesqui answered 15/3, 2012 at 10:44 Comment(1)
Your content-type doesn't appear to match your content…Asquint
C
5

It's simply not possible. AJAX requests never cause user prompts.

However, you can simply make the request return e.g. JSON or plaintext containing the URL and then use location.href = ...; to redirect to it; this will result in the prompt you are looking for.

If the request always results in a file download, you could also consider using a regular form and not using AJAX at all; if the response triggers a download dialog the previous page will remain in the browser window anyway.

Cylinder answered 15/3, 2012 at 10:45 Comment(2)
OK, so no wonder I'm going crazy :) But how do I get the return data to include the URL? My new version of the site is straight HTML & AJAX, and the PHP just sends JSON data to inject, not the HTML itself. The old version had PHP pages echoing HTML forms, but the URL was blahblah.php so you didn't have to include the URL in the HTML there either. I just don't know how to include the URL in the AJAX return data! (Please excuse the ignorance.)Sesqui
Actually, the more I think about it, the regular form idea might work well. (I'd still be very interested in an answer to the question in the previous comment, though!) Thanks for the help.Sesqui
M
-1

Why you do not link straight to print.php

and call php output to the 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);
Mandelbaum answered 15/3, 2012 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.