Can you request a download based on the submitted forms as part of the ajax response?

I use AJAX POST to submit form data to an external script and try to hide the form when submitting and ask the user to load the script.

The script itself works (uses fpdf to output a pdf file for download). For some reason, a user download request never comes.

My Ajax request currently:

$.ajax({ url: "file.php", type: "POST", data: data, cache: false, success: function (html) { //hide the form $('#form').fadeOut('slow'); //display results $('#form_results').fadeIn('slow'); $("#form_results").html(html); } }); 

file.php (by itself) will generate and display a PDF file using FPDF. By setting the output to I, the document will be output to the browser, setting it to "D", it will usually force download if I just accessed the .php file directly.

any ideas?

+4
source share
2 answers

Unfortunately, you cannot force download files directly from ajax call. It is best to submit the form via ajax and ask ajax to provide a URL so that you can redirect the user to start the download. However, only FYI, using location.href on the page that sends the header to force download in IE, will result in a yellow security bar at the top of the page. This happens in IE8, not sure about other versions. FF and Chrome have no problems with it.

Edit:

Just wanted to add, when you redirect someone to a page that forces you to download, they actually do not leave the page on which they are currently included. Therefore, they will not have to reload the ajax page or anything else. A download dialog will appear. So if you are on index.php and you say location.href = 'download.php', and download.php forces you to download. You just get the download dialog and don't leave index.php.

Edit2:

in fact, there are quite a few questions about this.

https://stackoverflow.com/search?q=force+download+over+ajax

+1
source

The problem is that you are trying to show results, but in a form that is hidden. Try something like:

  //hide the form $('#form').children().fadeOut('slow'); //display results $('#form results').fadeIn('slow'); $("#form results").html(html); 

Thus, each child will be hidden, but the parent himself will not.

0
source

All Articles