As you noticed, your AJAX call cannot directly output the PDF to the browser. One solution is to remove AJAX and send the user directly to the page that creates the PDF file. This approach is very common and well documented. But there is a way to use AJAX to create a PDF file so that the user stays on the web page until the file is ready.
Your AJAX call can answer using a JSON object with two exclusive fields:
- "pdfurl" if the PDF file was successfully created and written to disk,
- "errormsg" if an error occurred.
Something like (in PHP):
<?php //... if (writepdf($filename, ...)) { $result = array('pdfurl' => '/files/' . $filename); } else { $result = array('errormsg' => 'Error!'); } echo json_encode($result);
Then the javascript page may contain (jQuery example):
$.ajax({ type: "GET", url: "ajaxcreatepdf.php", data: {userid: 1}, dataType: "json", success: function(data, textStatus) { if (data.pdfurl) { window.location.href = data.pdfurl; } else { $("#messagebox").html(data.errormsg); } } });
user699082
source share