Is it possible to have an HTML form POST command that does not reload the current page?
I'm writing an SPA using Angular.JS and PHP, and the PHP code creates a PDF file that I want the server to spool to a local printer OR send to the client (depending on the client being a PC or a mobile device), so I believe I need a POST to download the PDF file, but in some cases I don't need the file download, hence I want the server to send a 'do nothing' response to the browser.
I can work around by using an AJAX request first, and depending on the response perform a POST, but was wondering if it was possible to minimise server communication.
Thanks
You can use an iframe and only the iframe will be reloaded. Here an example :
var onDownloadButtonClick = function() {
var iframe = document.getElementById('download_iframe_id');
if(!iframe) {
iframe = document.createElement('iframe');
iframe.setAttribute('src', '/path/to/your/file/');
iframe.setAttribute('id', 'download_iframe_id');
document.getElementById('iframe_parent_id').appendChild(iframe);
} else {
iframe.src += ''; // to reload iframe
}
};
document.getElementById('btn').onclick = onDownloadButtonClick;
And in your PHP file, you do something like this :
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo 'File don\'t exist !';
}
?>