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
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.
Related
code at controller side is given below
try {
$this->load->library('m_pdf');
$querytype = "advance_search";
$showdata = [];
$pdfFilePath = utf8_decode("download_pdf.pdf");
ob_start();
$body= $this->load->view('result/pdf_generation', $this->common_advance_search($querytype),false); //here i am loading view for pdf
$this->m_pdf->pdf->WriteHTML($body);
$this->m_pdf->pdf->Output(FCPATH.$pdfFilePath,'F');// till here i can see the data in view
$result = ob_get_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/pdf;base64,".base64_encode($result)
);
die(json_encode($response));
}
catch(\Mpdf\MpdfException $e) {
echo $e->getMessage();
}
Ajax Code
$.ajax({
url : "<?php echo base_url(); ?>"+scr,
method:"POST",
data:formData,
contentType: false,
cache: false,
processData:false,
dataType:'json'
}).done(function(data){ // here i am able to download the pdf in the browser
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","file."+ext);
$a[0].click();
$a.remove();
});
result is given below
check result (screen shot added here)
with this code, it is giving me a currpted PDF file, i am able to get data and 'Export as pdf'. I have checked whether it is passing data from view, and yes it is doing so. But don't know what is the matter . I is printing everything outside it is working fine, Can anyone please let me know what should I do?
I am working on a project for graph print.
I call data by ajax and it gives data but when I want to use it.
console gives error no data specified .
function ajax_call(){
$.ajax({
type:"POST",
url:"ajax_process.php",
data:{curr:curr},
success: function(result) {
// alert(result);
$(".output").html(result);
// global_value=new Array();
// global_value=[1.23231,1.23231,1.32311,1.43421,1.34531,1.2313,1.1234,1.232,1.1121,1.431];
global_value=result;
alert(result);
show_graph(result);
}
});
}
function show_graph(global_value){
alert("GB"+global_value);
...// CODE
}
When I want to print result it gives error but global value which is static not gives error. I want to use result data . Thanks !!
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:
$.ajax({
url: base_url+"controladorapr/exportComprobanteIngresos", //method i called
data: $(this).serialize() //i serialized data from a form,
type:"POST",
dataType: 'JSON',
success: function (data) {
//create a link to download the pdf file
var link=document.createElement('a');
//i used the base url to target a file on mi proyect folder
link.href=window.URL = base_url+"exportacion.pdf";
//download the name with a different name given in the php method
link.download=data.nombre_archivo;
link.click();
//this js function hides the loading gif i use
hideLoad();
}
});
Now, let's head to the method on my controller:
function exportComprobanteIngresos(){
//receive your ajax data
$fecha = $this->input->post("fecha_comprobante_ingresos");
$fecha = date_format(DateTime::createFromFormat('d/m/Y', $fecha), "Y-m-d");
//send data to pdf
$data["fecha"] = $fecha;
//do some query here to send data and save it into $data[] array
//pdf size
$tamaño = 'A4';
//create a file name
$nombre_archivo = "Comprobante_ingresos".date_format(DateTime::createFromFormat('Y-m-d', $fecha), "Y_m_d").".pdf";
//load dompdf method, i will show this later, and send the data from db and file name
$pdf = $this->pdf->load_view("pdf/comprobanteIngresos", $data, $tamaño, $nombre_archivo);
//save the pdf content into the file we are downloading
file_put_contents('exportacion.pdf', $pdf);
//send data back to javascript
$data2["nombre_archivo"] = $nombre_archivo;
echo json_encode($data2);
}
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':
$dompdf = new Dompdf();
$html = $this->ci()->load->view($view, $data, TRUE);
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper($size, 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to variable and return it to save it into the file
$output = $dompdf->output();
return $output;
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!
I am here to ask that is there any settings argument in jQuery ajax() which let us to call a function when data has transferred to php file successfully not when the data has transferred and php file parsed the code and returned a value.
I have following code:
$.ajax({
..
..
..
success: function(data) {
// do something
}
});
But I want it like:
$.ajax({
..
..
..
onTransfer: function() {
// do something like show a div saying "Done".
},
success: function(data) {
// do something
}
});
You only get 1 answer from server side, what's wrong with success? If your process takes too long then you could return from script as soon as it get's started and show 'Processing your request' as result for success:
<?php
ob_end_clean(); // discard everything
header("Connection: close"); // send Connection close
ignore_user_abort(true); // ignore user abort
set_time_limit(0); // no time limit
ini_set("memory_limit","200M"); // setup a memory usage needed
ob_start(); // start output buffer
header("Content-Length: 0"); // send lenght 0
ob_end_flush(); // end and flush
flush();
// continue your script
Your script will continue to run while you receive a success answer from it.
You might use it like this
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
For more details please check following link
http://api.jquery.com/jQuery.ajax/
I want to get a watingmessage in extjs while loading a link. The response is a binarycode, which I want to downlad. The link is for example "test.php".
function loadurl(link){
Ext.MessageBox.wait('Loading ...');
Ext.Ajax.request({
url: link,
callback: function(options, success, response){
Ext.MessageBox.updateProgress(1);
Ext.MessageBox.hide();
if (success) {
// response : my attachment
}
else {
}
},
scope: this
});
}
{
...
//functioncall
loadurl('test.php');
}
I also tried in test.php.
<?php
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $content;
?>
But it doesnt work. If I just load the link it works, but without waiting message.
In the ExtJS Documentation there is a class called LoadMask which is designed to show a loading 'spinner' along with a short message. In your case, you would use it like this:
function loadurl(link){
var mask = Ext.LoadMask(Ext.getBody(), {msg:"Loading..."})
mask.show();
Ext.Ajax.request({
url: link,
callback: function(options, success, response){
if (success) {
// response : my attachment
}
else {
}
//do whatever work we need to do, then hide the mask
mask.hide()
},
scope: this
});
However, if, for whatever reason, the callback comes back almost immediately, then it is possible that the mask will not be visible because your file loaded too fast. If this is an issue, you could force a delay by putting your Ajax request inside a setTimeout.