I have a method, which calls the backend through AJAX, to get a blob file from MySQL database, which is retrieved by PHP.
The problem is that the PHP variables contain a string, but the AJAX call comes out empty and the PDF function does not work.
Here is the AJAX code, which is getting called.
self.showPDF = function() {
$.ajax({
type: 'GET',
url: BASEURL + 'index.php/myprofile/openUserPDF/' + auth,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
})
.done(function(data) {
console.log(data);
window.open("data:application/pdf," + escape(data));
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Could not open pdf" + errorThrown);
})
.always(function(data) {});
}
This is the PHP function in the backend, I am using the CodeIgniter framework.
public function openUserPDF($token) {
if ($this->input->is_ajax_request()) {
$userid = $this->myajax->getUserByAuth($token);
if ($userid) {
/* If we have an impersonated user in the session, let's use him/her. */
if (isset($_SESSION['userImpersonated'])) {
if ($_SESSION['userImpersonated'] > 0) {
$userid = $_SESSION['userImpersonated'];
}
}
/* now we get the pdf of the user */
$this->load->model('user_profile');
$images = $this->user_profile->getUserImageForPDF($userid);
$pdfString = $images[0]->image;
$this->output->set_content_type('application/json');
return $this->output->set_output(json_encode($pdfString));
} else {
return $this->output->set_status_header('401', 'Could not identify the user!');
}
} else {
return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
}
}
I do retrieve the blob as a string, but that's basically it, it doesn't return back to the AJAX call.
It's a really, really, really, really, really bad idea to load the potentially huge contents of a PDF into memory when you could simply use file_get_contents
or readfile
to output it directly.
Javascript
self.showPDF = function() {
window.open(BASE_URL + '/index.php/myprofile/openUserPDF/' + auth);
}
PHP Function
//... validation and querying ...
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
readfile($pdfString);
(headers from How to render pdf file by using php; see for more information on rendering PDF files using PHP)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With