jQuery, Codeigniter and DOMPDF: Anchor works but not AJAX
I have the following anchor tag that when pressed, successfully calls a function (my_pdf) within the controller (main).
<a href="main/my_pdf">Press Me</a>
Here's the function in the main controller:
function my_pdf()
{
$this->load->helper('dompdf');
$this->load->helper('file');
$html = "<p>Testing</p>";
pdf_create($html, 'somefilename');
echo "Your PDF has been created.";
}
The DOMPDF library works and creates the file "somefilename.pdf" as expected when it is called by an anchor tag or when browsing to the controller/function from the URI as follows:
http://localhost/main/my_pdf
Instead of the anchor, however, I need to call this function from a jQ开发者_C百科uery AJAX request. Here is the html:
<div id="pdf"><img src="assets/images/pdf-icon.gif" /></div>
<div id="notice"></div>
and supporting jQuery:
$('#pdf').click(function(){
$.ajax({
url: 'main/my_pdf',
type: 'POST',
success: function(msg) {
$('#notice').html(msg);
}
});
return false;//toggled this between true/false and still not working
});
If I comment out the pdf_create call in the my_pdf function, I confirmed that the AJAX call returns the echo string to the as expected. The problem is that when I use AJAX to call main/my_pdf, the pdf is not created. In fact, it appears that pdf_create returns a long string of code to that is likely supposed to be used to render the pdf. The AJAX success message returns the following string:
%PDF-1.3 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R /OpenAction 8 0 R >> endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type /Pages /Kids [6 0 R ] /Count 1 /Resources << /ProcSet 4 0 R /Font << /F1 9 0 R >> >> /MediaBox [0.000 0.000 612.000 792.000] >> endobj 4 0 obj [/PDF /Text ] endobj 5 0 obj << /Creator (DOMPDF) /CreationDate (D:20110225190447-05'00') /ModDate (D:20110225190447-05'00') >> endobj 6 0 obj << /Type /Page /Parent 3 0 R /Contents 7 0 R >> endobj 7 0 obj << /Length 73 >> stream 0.000 0.000 0.000 rg BT 34.016 723.208 Td /F1 12.0 Tf [(Testing)
I'm open to any suggestions.
From what you understand, you want your ajax call to show "Your PDF has been created." in the #notice
element, and have the pdf generated in the background.
The problem in what you are doing now is that my_pdf() actually echoes out the contents of the generated PDF file, which is where the %PDF-1.3 1 ...
string comes from. If (and I believe you are) you are unsing this dom_pdf helper you need to set the third parameter to pdf_create()
to FALSE
, so that the pdf is generated but not echoed out, like this:
pdf_create($html, 'somefilename',FALSE);
The only thing that will be echoed is "Your PDF has been created.", which will display correctly after your ajax call.
Note also that you can greatly simplify your ajax call by simply doing:
$('#pdf').click(function(e){
$('#notice').load('main/my_pdf');
e.preventDefault();
return false;
});
精彩评论