问题
I am trying to return a tcpdf after validating a form. If there is an error in validation the php file returns an error msg. If the validation succeeds I want to return the PDF. Trouble is that when the pdf is returned it is not displayed as a PDF just garbage text. What change do I need to make in my code?
Here is my ajax submit code:
function postForm() {
var ajaxRequest;
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $("#matchReportForm").serialize()
ajaxRequest= $.ajax({
url: "mReport.php",
type: "post",
data: values,
beforeSend: function() {
$('#result').html('<img src="images/indicator.gif" alt="loading..." />');
$('#btnGo').attr("disabled", "disabled");
$("#txtSecurity").focus();
}
});
ajaxRequest.done(function (response, textStatus, jqXHR){
// show successfully for submit message
$("#result").html(response);
$('#btnGo').removeAttr("disabled");
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// show error
$("#result").html(response);
$('#btnGo').removeAttr("disabled");
});
}
In my PHP file I either echo an error msg or return the pdf:
$pdf->writeHTML($report, true, false, true, false, '');
$pdf->Output('match_report.pdf', 'D');
回答1:
You can't show directly a PDF into a div for the obvious reason that it's not HTML. But you can embed it in your page using this:
function postForm() {
var ajaxRequest;
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $("#matchReportForm").serialize()
ajaxRequest= $.ajax({
url: "mReport.php",
type: "post",
data: values,
beforeSend: function() {
$('#result').html('<img src="images/indicator.gif" alt="loading..." />');
$('#btnGo').attr("disabled", "disabled");
$("#txtSecurity").focus();
}
});
ajaxRequest.done(function (response, textStatus, jqXHR){
// show successfully for submit message
var pdf = $.base64.decode($.trim(response));
$("#result").html('<embed width=100% height=100% type="application/pdf" src="data:application/pdf;base64,' + escape(pdf) + '"></embed>');
$('#btnGo').removeAttr("disabled");
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// show error
$("#result").html(response);
$('#btnGo').removeAttr("disabled");
});
}
Like base64 data image you can include a PDF in your page as a binary stream.
来源:https://stackoverflow.com/questions/35197218/return-tcpdf-after-server-post-ajax-issue