I have this PHP File called print.php:
<?php
require_once("modules/pdf/dompdf_config.inc.php");
$html = $_POST["toRender"];
$number = $_POST["number"];
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream($number.".pdf");
As you can see, the HTML and a Number are received via POST.
The JavaScript file looks like this:
$("#btnViewPDF").click(function() {
var theHtml = $("#printable").html();
var theNumber = $("#invoiceNumber").val();
$.ajax({
type : "post",
url : "views/print.php",
data : {toRender : theHtml, number : theNumber},
beforeSend: function() {
$(".ajax-loader-bg").fadeIn();
}
}).always(function() {
$(".ajax-loader-bg").fadeOut();
});
return false;
});
Basically it takes all the content inside a DIV called 'printable' but what I want next is the PDF that has been generated in print.php to be displayed, I haven't been able to figure out how can I make this.
I've made it work when I generate test HTML inside print.php and then I type in the url mysite.com/print.php ... it renders the PDF and allows me to download it or see it in another browser tab.
How can I achieve this via AJAX?
You can't download something via AJAX, you could simulate the behavior using an hidden iframe.
Not that you can't download it, but, it will never end up in the filesystem for saving purpose because javascript can't do that for security reasons.
Anyway people always find solutions, you can try this: https://stackoverflow.com/a/23797348/1131176
i did achieve this, by doing just a trick, this example is made in codeigniter, so you can adapt it, first, the ajax method:
Now, let's head to the method on my controller:
}
now, we will include dompdf, to use dompdf on codeigniter see this answer: Codeigniter with dompdf
Now, this is the code from dompdf i use in the function '$this->pdf->load_view':
now with this, i managed to use ajax with dompdf and put a loading gif to it, and it works great, by last, the php file you load on '$this->pdf->load_view' doesn't have a header or else, is pure html and php, hope this helps!