Search code examples
phpjqueryfpdf

FPDF error while creating class


I've a problem with creation af the class needed for outputting JSON data to PDF. The PHP file is as following:

<?php    
header('Content-type: text/json');    
ob_start();    
require('fpdf.php');    

class PDF extends FPDF{    
  // Colored table    
  function FancyTable($PDFtabHead, $PDFtabData)    
  {    
    // stuff with table works if tested with another PHP page    
  }    
} // END -class    


$PDFtabHead = json_decode(($_POST['PDFtabHead']), true);    
$PDFtabData = json_decode(($_POST['PDFtabData']), true);    

$pdf = new PDF();    
$pdf->SetFont('Arial','',12);            
$pdf->AddPage();    
$pdf->FancyTable($PDFtabHead,$PDFtabData);    
$pdf->Output();    
echo json_encode(array("res"=>$PDFtabHead)); // Only to chek if outputs something    
ob_end_flush();    
?>    

The caller function from my JS file is:

$.ajax({
    type: "POST",
    async: false,
    url: './FPDF/PDF.php',
    dataType: 'json',
    data: {PDFtabHead: tabHead, PDFtabData: tabData},
    success: function (response) {

      var res = response.res;
     console.log("ok return: "+res);
    } // success
    ,
    error: function() {
      console.log("ERROR CONNECTING TO ./FPDF/PDF.php");
    }// error

  }); // ajax

tabHead and tabData are correct, this is the output of tabData :

["05:22","0043","22:31","200201","05:22","0044","22:31", ......]

The call to PDF.php always ends with error, outputting to console : ERROR CONNECTING TO ./FPDF/PDF.php

If I test it from another test page that doesn't send data in JSON format, but a normal PHP Array it works. Obviously I have to change to

$PDFtabHead = ($_POST['PDFtabHead']);
$PDFtabData = ($_POST['PDFtabData']);

in this case PDF page is rendered correctly.

Similarly if I delete the class declaration, and simply return back to my JS page the JSON array, it works; doesn't print PDF it's clear but the Array is returned as expected


Solution

  • OK I've got the solution at the FPDF forum http://www.fpdf.org/?go=forum&i=56364&t=56363, Oliver's answer is

    Don't return a PDF from an AJAX call.