I am trying to use AJAX to query a PHP file and display a PDF file to the user. The response from the PHP file is the raw data of a PDF file stored on my server. Below is the code I am using to try and accomplish this but it isn't working. I keep getting a bad request error from my browser. Does anyone know the right way of doing this?
My end goal is I do not want the user to be able to see the server path where I store my PDF files. I only want the PDF files to be accessible using the AJAX / PHP script. I understand it's not the most secure method but I just want to keep the layman away from my PDF files.
$.ajax({
type: "POST",
url: 'process.php',
data: {"name" : "value"},
success: function (data) {
var json = $.parseJSON(data);
if(json.hasOwnProperty('success')){
window.location(json.success);
// json.success should contain the pdf binary data
// i just cant figure out how display the pdf in the browser
}
}
});
<?php
$fileName = $_POST['name'];
if(isset($fileName)){
$file = './path-to-forms/'.$fileName.'.pdf';
$pdfData = file_get_contents($file);
$data = array("success" => $pdfData, "name" => $fileName);
echo json_encode($data);
}
?>
Does anyone know the right way of doing this?
A couple changes should get the file downloading correctly:
Update the PHP code to send the file contents using base-64 encoding (i.e. with base64_encode()):
$data = array("success" => base64_encode($pdfData));
When the AJAX response completes, create an anchor (link) and simulate clicking on it using .click() to initiate the PDF download. I can't find any jQuery method window.location()
on api.jquery.com... if you find it, let me know. Maybe you were thinking of updating the (read-only) property window.location?
var json = $.parseJSON(data);
if(json.hasOwnProperty('success')){
var a = document.createElement("a");
a.href = 'data:application/pdf;base64,'+json.success;
a.download = "filePDF"; //update for filename
document.body.appendChild(a);
a.click();
// remove `a` following `Save As` dialog,
// `window` regains `focus`
window.onfocus = function () {
document.body.removeChild(a)
}
}
Credit to guest271314 for the adapted code from this answer along with some of the code from Alexandre's code in the answer below that.
See it demonstrated in this phpfiddle.