I use AJAX POST to send form data to an external script and attempting to hide the form on submit and prompt the user to download the script.
The script itself works well (uses fpdf to output pdf file for download). For some reason, prompting the user to download though never comes through.
My Ajax request is 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 (on it own) will generate and display a PDF using FPDF. By setting the Output to I, the document is output to a browser, setting to ‘D’, it would normally force a download if I were simply accessing file.php directly.
any ideas?
Unfortunately you can’t force a download directly from an ajax call. Your best bet is to submit the form through ajax and have ajax respond with a url that you can redirect the user to that starts the download. However, just an FYI, using location.href to a page that sends a header to force download in IE will cause the yellow security bar to appear on the top of the page. This happens in IE8, not sure about other versions. FF and Chrome don’t have a problem with it.
Edit:
Just wanted to add, when you do redirect someone to a page that forces download, they don’t actually leave the page they currently are on. So they won’t have to reload an ajax page or anything. The download dialog will just show up. So if you are on index.php and you say location.href=’download.php’ and download.php forces a download. You just get the download dialog and don’t leave index.php.
Edit2:
there are actually quite a few questions about this already.
https://stackoverflow.com/search?q=force+download+over+ajax