I am new to php and ajax. Im trying to force download a file from a list of documents. The functions below gets triggered using an ajax call after a button click.
function downloadDocument($filename) {
$file_path = ".........../DocUploader/Uploads/" . $filename;
if (file_exists($file_path)) {
header("Content-Description: File Transfer");
header("Content-Type: application/json");
header("Content-Disposition: attachment; filename=\'" . $filename);
readfile($file_path);
} else{
echo "Document does not exist";
}};
Instead of downloading the file, I assume I am getting the file content as a response. I would really appreciate any advise on what I should do.


First remove any echo's or output to the browser before sending any
header, ie. remove theecho "File exists";The file name should be encapsulated in quotations, ie.
Content-Disposition: attachment; filename="filename.ext"Keep in mind to set correct
Content-typebased on the real kind of the downloaded document, see topic What are all the possible values for HTTP "Content-Type" header?You can dynamically detect the MIME type using PHP function mime_content_type()
And reference for PHP header.