文件下载Ajax操作

A dynamically generated files (According to user inputs) need to be downloaded...

I have been using mPDF (php module to create pdf files).

gen.php

require("./MPDF56/mpdf.php");
$mpdf=new mPDF();
$mpdf->WriteHTML('<p>Hallo World</p>');
$mpdf->Output('filename.pdf','I');

This scripts works perfectly. Output method can have several options Like

'F' : to save pdf to local.
'S' : to return file as string.
'D' : to download the file.
'I' : force download... plug-in if available.

http://mpdf1.com/manual/index.php?tid=125

whenever a browser read the gen.php. pdf file will be downloaded. As i said it works perfectly ...

Until , i try to do this with ajax.

This script...

$.ajax({
  type:           'POST',
  cache:          false,
  url:            './gen.php',
  data:           JSON.stringify(inps),
  contentType:    'application/json',
});

triggers the gen.php. PDF file is created. However, file is not sent to the browser.

If i add this to the ajax part...

success: function(response){
  $("#result").html(response);
}

Document receives the file as a string. I tried all the options of the mPDF.OUTPUT function . no result.

I thought a work around but i dont know how to achive it.

Ajax need to open a pop-up while it sends the data. So File-download operation will be done under another tag.

Or maybe. I can try to open a invisible iframe of gen.php and send the data after i frame created...

Any suggestion will help.

SHORTLY

How can ajax call a php file (that downloads a file). After the necessary data is sent.

I think the question asked in the title of this post is answered here: Download a file by jQuery.Ajax

But there may be a simpler way to accomplish your goal, as I understand it. If you need to send information to the gen.php script and you're concerned about size of data sent to prepare the PDF and how an HTTP GET may handle that, use a FORM POST instead:

<form action="gen.php" method="post">
    <input type="text" name="X">
    <input type="text" name="Y">
    <input type="text" name="Z">
    <input type="submit" value="Download">
</form>

If mPDF responds with the appropriate headers, and I expect it does, the main page does not reload, but the file is sent to the browser for download.