6

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.

user7637745
  • 965
  • 2
  • 14
  • 27
Masnad Nihit
  • 1,986
  • 2
  • 21
  • 40
  • Possibilities: 1) you seem to be returning the pd f'string' as json. I am not sure that is going to work - maybe better as simple text; 2) the utf8 encoding will screw up some of the PDF data (maybe); 3) the method of creating the new window looks dodgy - afaik the window.open() command expects a URL. – Vanquished Wombat Dec 29 '16 at 12:03
  • @VanquishedWombat 1) so should I convert the string as simple text? 3) I looked up a lot of opening pdf commands, but could not try any of them since no data was returning so its there but not been used. – Masnad Nihit Dec 29 '16 at 12:12
  • Sorry not an expert but I can see those few suspect issues. I would google for 'load display pdf from database ajax' and see what you find. Hopefully some working code or tutorials that you can adapt. Be sure to refine your question if needed and post the answer if you find one based on what you learn. Good luck. – Vanquished Wombat Dec 29 '16 at 12:15
  • Please visit this link here you can found answer. Link : http://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download. – Bhavin Dec 29 '16 at 12:19
  • @Bhavin I am not downloading the file, I just want to open it in the browser. – Masnad Nihit Dec 29 '16 at 12:20
  • @MasnadNihit. Yeah but your main logic is Detect when browser receives file. So from above answers may be you can found your answer. – Bhavin Dec 29 '16 at 12:22
  • @Tried the code one, did not work. – Masnad Nihit Dec 29 '16 at 12:23
  • I'm not sure that loading the PDF content with AJAX into the client's memory is a good idea. Why not just do `window.open(BASEURL + 'index.php/myprofile/openUserPDF/' + auth);` and output the content as application/pdf directly from the server? Sure, if there's an error, the user will have an "ugly" new tab, but it's way easier. actually, you could call the PDF with AJAX and then open it again in a new tab. This 2nd call will load it from the browser cache (if enabled) or in the worst case from your server cache (if enabled) – masterfloda Jul 11 '17 at 00:13
  • You could simply NOT use ajax and open the url in a new window, there you simply have to send the header, echo the file content and shutdown your request. I know this does not anwer your initial quesion, but it solves your problem in the exact same way (new window -> pdf content). – Philipp Wrann Aug 02 '17 at 06:54
  • Please, test with a small PDF. There is why: https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers – Bruno Minossi Mar 30 '18 at 04:38
  • I hope below link will help in your case. https://stackoverflow.com/questions/34586671/download-pdf-file-using-jquery-ajax – Gaurav Mall Dec 21 '18 at 04:42

1 Answers1

1

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)