Reputation: 308
I am creating simple file downloading script using AJAX in PHP. My script is not working. Means it displaying the content of the pdf/doc file below download link after clicking on it. Below image will illustrate the problem.
Below is my code
AJAX and HTML:
$(function() {
$(".download_link").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
$.ajax({
type: "POST",
url: "download_file.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
}
});
return true;
});
});
<a href="#" class="download_link" id="d_link">
PHP Script: (download_file.php)
<?php
ob_start();
$file = 'file.doc';
header("location:".$file);
?>
Upvotes: 0
Views: 1824
Reputation:
You are using $("#display").after(html);
thats why its displaying the content of the file. You can download the file by following code.
$(function() {
$(".download_link").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
$.ajax({
type: "POST",
url: "download_file.php",
data: dataString,
cache: false,
success: function(html){
window.location = 'your_file.pdf';
}
});
return true;
});
});
Upvotes: 2
Reputation: 621
I think your approach is incorrect.
With your script you are trying to append file.doc contents into DOM object -> browser do not know on AJAX request how to manage document's encoding, it will not work.
For downloading documents I would not use AJAX, I think would be fine if you just open a new window with the document's url and let the borwser to manage the content's response:
window.open("download_file.php");
If you just want to display documents contents in the same page, I would use an iframe as follows:
<form action="download_file.php" method="GET" target="docIframe">
<input type="submit" value="Download"/>
</form>
<iframe name="docIframe" width="600px" height="500px"/>
Upvotes: 0
Reputation: 2551
You need to set header content type to tell the browser how it renders the content for PDF or DOC.
<?php
//Set header for pdf
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='file_to_download.pdf'");
readfile("original.pdf");
?>
Upvotes: -1