I cant generate pdf with fpdf and ajax - javascript

Excuse my bad English.
I have a problem, I try to generate a PDF file with the fpdf library in a php (controller) passing before by an AJAX (jscript), but it does not generate the pdf but it generates this
PNG
IHDRd'©ñ :IDATxíAÇßFÊÆ
(l£Mb1ö`á\6ÓÆí!°gÉ-Ö$\Ârçl4öÁø0"¶7Y#´'BwQÌ
áY¬Äe1rÍ¡µ­ÞªêW¯ª«»§·ÿcõôT½÷êUõëWÕÕ³s³Íááa|ðjí9§ãÖ4îß¿_µ ¨\¸p¡jf¹¹¹ôÇÓDô""zóø
áÕªM#¥£Ç~9<<üÓÖnµ¦TÂÒSòù`q19FÀty-Wb-®ÂÛbêÙ="iî1c-c.5JTÝY¹Qj
ø$ÃúìRTQÕ±bÅ#5kdë(ãûÅÅg-"Ì=rÒîÕ}Ë´+éÁt½¼ÒÑÆZ9iæÅÈpýúõv»MqÀú
ѯ¾ÿé¤j«*!#å~7®ohA÷¾º³#¼ða.l-+M½MÝÈ°vãäöë4ú³æƤD~:¯LÓZä8áûÙhFr>+ú(JXËf^°,ÃÒ2F6ùÉ+fÅ)¡Ö¤1Æ'uÖX¿XÕN1ú*«øZ`
+!^Ãzã7L aüMÇG¹q¿]~)\õ+I&%0È9£UdyB|e¡£¬a½¥ Ìäú'¿6¾­¨¹£ ¬a¥ÉaötOþ¸lBFɶ¬S?I­<4ób+o׬+DÊAfõhUÄev¨ò¼É·ÉGö¬Z9iêÅhVVz¼f]!ɱ±þ­U"×åñ¤7ÞvRÅieØÏá·^g-f^ð°5¬2ÓL©Âr⨧ xJxB 4*TÅ4ób5¬B2¬2¯±^Ï'¦^&°æ³ª
ÈAa'RøÅQ#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔX+¢ôéóJ1æcíÁeúIfÊ5l¶É/v}xZùü<}~)ÙFéºé
GãI¨Ic£ ®:å¥fXåG+W¥ÆlK¿-èÅÒg²j¥IznåRÄ¢%»êÒR%y¢öPöxøGÞvW9m®º¬c#Ëå8T-I¿AÍ°fÄÉ­ÜâÊeÒ¯Ò:FáFE®­¤¤íIk4O·ÇØ.«ÍúU²ÑÖ2
[ªgÀsü81']JKí2jw­%ìÁ°®´îìîþçìÙ3wéÅ ü¯×Òc:z¨hg$[C¡R2>ÜÁüÊè6ëVÉ©q±ÁûÇZ]ÒR=ÆI,ô0^1F ñNä«NJýr"½±Nýëß7ÚQ|¼´ôÃ~ÿMË/6,ÞCGYF¹ZÆ©à1¿VPaVèâTz<çô¡~¦~ÏûðÛ»FDtñâVëÔx¼Õí¾Â0ÂN¡FèªÆ0AD.ÙÉØ-ÆA/ôXÛ»W¢PÕÂsvVWXÕÊaõû$¢µµ¨ÓYØÞÞ¿víãñV{ûï/þ4yæ»7åéÔ($íÇà÷Õ¢%3¤µÝXÆ*ÙÏÒ,ñ^FèCIKõ±aÕ.!T/gy>-S¨Ki©N­ÃO®=¹þÌ×Wã÷úý÷£h~4z!>3ìÞ¸1iµÎF¿Á!(2I
ý/?®F÷ÚkDÔé<¹Wt:£Ñ&ýáðÖw°N2¥ÝTHð_ÃoM§ûQ4ßnKïv%¢Á`t¥u'¯u` !Z2ñXW£{7oÞ¢£ôjsó¿Îv¯·3,/?½´Ô¢£å-gÀJ§WÉ£n÷_ãñt4ú²ß#D½Þ"mn~raïv#[
Ç'`)éÕx<M¾£h~uõ<õûïç´o%ûu'!Åüjì§Ô[xiùõ§ÝE<ÿv¸wĻתm+y¬-bòø¬¬Õ+":{öñ*~§µZ§¶¶|sûCoãV^˨v×LC(m5*kÛaèÛÖõQW¹Q¯v9?%¼Ýkß¼EGëDEóÉ·­Ö©ä Óúýýþû£Ñåü[ÒnUv]髲`1àí'Nº²jåÌÒðöl¬¢ï÷ÃìÝ4½í~ö0ÝÇqc­ÅTÔÛ¥û'½C«YþqêwI-ïqhÅ9`ÅéÕÒRkyùéøL¤VWÏß¼ùEð-+Ç_,0vq¸óÛF]tÜûë/åzHØ®nµGâ%k+þwŨËolHòw«½ccµi¬µÿóþ´7&«]ÞãÐ[ÀºÒº³zó­­-$'/^<U¾×[ìt¶Ñ¨ýÒߦ/ø¨ 7"9}䤫4ÉéA&©åasúVÌGyå#×ÊcýƱ5]ÊÌ?å+W?;¡Á8ÊCi ãPÇ-`
£8½7.褧D§½Þ»/wûþf²½ÿoÌ·CáaÄo­·t¦V~í*ýîRVê/??K.0BǡâûÖÑèc:^Å$ñ+¾¥|oq·rnqðk¤µ
Xvf1ÊI'ÕéË© ֵת®÷y?ÂÕ
öósAM
/aê8dXñ¯20éxÃpø°×{÷oþØɸt/J_ôi¹>¬ãH
èC¿Ï%;iØc,£Ì¬>d`úB+ú-7}Æi>®el;sƨ]Çê­Ç7£KJöè÷BÇ¡éËÏWZwÚíßÑ`pQXýþáð!ýlòítzÐnßNºÝ=µôso[AÓp(1«G·äågéO¯Z­ÇÚ¼éÛSñÓÁ`ãjtÏËlÐ Vv#QÀbV¯b8¥,º'¬®¢ùét0Øð²4u¯×ªÝ(`ÅéUòV³NVJ¯¾Å¯8ü°¬$½J¶¶ëdíMì5íõÞu0°¬øWbÚísLìå#WòòoqÈ"çÓBûé*ͤÓ_V,̨ʨ¼QÆÞVYûɬÄKuaïöææ'tügEln^^`v½Qͯ­E$KÓ3²üü¶YæÑ÷ßÚ
í±ìúqcléM&VWÿ1ôû?HÞ14ríÚùáðÉä˯ÆïI¶87+{¬Û ZiÉBQéZÆ3V(º$í´Bh'o¤øyC²ÍZKØËV]ƶj¤¿óÒÂ|CÞñn©b°íAàÖ½Ûãñ Ò«/§Ó"ò«Õ:Õí>Ûëí£ÑKÖ_qÐ;F9HdädÕJÎ('öHPÞ#ýfmp([{CEJ´[ûT¯bl=Ö²¶Ý¯%ökÉ\×dz??ûÁ¬áð Ò+"zåsÃáÓéAü»}<íö¹áðáööþhôñSK¥÷s0ÝÊeômÄjS&m¡¤S#¢« Úå}*¬Å+cl»®Âc
³]«a¼vNöäg.` W¯(æ77/O&$ûhuõ|¯·3oÿh+¦DnäB1Ú#¹q«¡ì×SÐ%7×îݧ4Ç ùHpˤur9ÏKʳïàÝ[­3D´·÷?¡,a´"¢ÝÝGÂ1AîÕé·,&¿ãËä1;IìaT¬y+WxÃCläl»k#\¼Î5*ÒÆa-/_>ît¶ùg®L§ÛÛû±ü¯Ùé4÷|¦ÏMøDW×eD¥ro¹d=B]:y#T´¶êeaYû]Òf¬*JÐ;~p/?_îu»oÅëîÁY]ýÉ÷^ùUd1TE =ÒNC¡è/?4yîån¿KßÛÛkÄÂÂwBýi)óÎf&wºý÷°îÒt6°ÖûS{ ¡C¶.×5Mîtÿ?U%¨
ÎæëÄ཯ uYOôZÆMÌp£aó=u+\ öSݥ밧ÏïÒ3%QR§·¡4f}¥?ïËz(Rd¿ºräUf$RT»8¡N ˼Òã?{¢lÌ*ìdI´n\Ñ~bERFX¿ôo³v6ëÙ¯](ÇZFâyÒlôüàNö;£9CUܽ3=%Ô³äf¨lqTÊëÅô«.£IÂ<(«SéøÄÍ(_¾Ëè±<Û®_ùç%ËóòÚõDI·º0ÓLCÖ8.­r$CS"'ëμîò²qÖ´N¿ø [íäKØö<zó'>Aú̳°\×hÊ×Åǹ"á4M^ØI²~mW\W(Y9)Ò«R¿m
In¯çkµA9ȧ2ë©÷ù²²ãwefµ(gÛé_Î+TÄx&>PlÎZèe2Ó~7ÖW©Ö3^×ÔçVéõ
ôânÀ|A1ÞÉ^;ãôì[ØvÅ«~63ºxíJ/ëe²lF¶U¤ù¹Ö`DήËÞ軳"ùà¼NX¸0f
×iiqÚQ¿Ew#cAÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ,#m#ÀÔ'?/ó7W¡ óÚk¯½óÎ;ÉÇÇÖ믿^= åqõöÛoÏÍÍUk
ð<ΰ­³ÏéÃÃÃôçëׯWe
ðÌ)ëöíÛU<ØÖ¨
ÿ/æ7JãpTÙIEND®B`
Here my code
The index calling ajax
index.html
$(document).ready( function()
{
//RESET MODAL CONTENT
resetModal("#myModal");
$("#btn_pdf").click(function(event) {
pdf_requerimiento("usuario", "tipo_maquina", "patente", "codigo_codelco", "hr_inicio", "hr_termino", "fecha", "hr_solicitud", "hr_operador", "hr_gps", "rendimiento_gps", "rendimiento_operador", "rendimiento_maquina", "rendimiento_usuario");
event.preventDefault();
});
});
The Ajax
function pdf_requerimiento(usuario, tipo_maquina, patente, codigo_codelco, hr_inicio, hr_termino, fecha, hr_solicitud, hr_operador, hr_gps, rendimiento_gps, rendimiento_operador, rendimiento_maquina, rendimiento_usuario) {
form = new FormData();
form.append("action", "pdf_requerimiento");
form.append("usuario", usuario);
form.append("tipo_maquina", tipo_maquina);
form.append("patente", patente);
form.append("codigo_codelco", codigo_codelco);
**...**
$.ajax ({
data : form
cache : false,
type : "post",
url : "pages/pdf/controller.pdf.php",
processData : false,
contentType : false,
success : function(data)
{
/*window.open(
'data:application/pdf,'+encodeURIComponent(data)
);*/
},
error : function(data){ alert('Error');
}
});
}
The controller
function requerimiento(){
//Variables
$usuario = $_REQUEST["usuario"];
$maquina = $_REQUEST["tipo_maquina"];
**...**
$pdf = new PDF('P','mm','A4');
$pdf->AddPage();
$pdf->SetFont('Helvetica','B',16);
$pdf->Cell(190,10,'Detalle del Requerimiento','B',2);
$pdf->Output('I','requerimiento_pdf.pdf');
/*
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="requerimiento_pdf.pdf');
*/
}

In php
header("Content-type:application/pdf");
and after
$pdf->Output('I','requerimiento_pdf.pdf');
First you have to set header. And only after that output document.

Related

Where do PHP echos go when you are posting to a page?

This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)

VichUploader and CroppieJS : how to send a base64 cropped image to persist in Symfony 4

I have a small symfony 4 application with a cropper using CroppieJS.
When i crop and hit the save button, croppie sends me a base64 image :
$( "#cropSave" ).click(function() {
basic.croppie('result','canvas'
).then(function (result) {}
how to send this result to my controller and persist the image with VichUploader and Doctrine ?
Here is my controller :
public function updateProfilePicture(Request $request): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$user->setImageFile($request->files->get('image'));
$entityManager->flush();
return new Response("ok");
}
I tried a lot of things but I must lack experience because it don't work :
var form = document.getElementById("myAwesomeForm");
var ImageURL = result;
// Split the base64 string in data and contentType
var block = ImageURL.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];
// get the real base64 content of the file
var realData = block[1].split(",")[1];
// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// Create a FormData and append the file with "image" as parameter name
var formDataToUpload = new FormData(form);
formDataToUpload.append("image", blob);
or
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
here is one of my ajax request :
$.ajax({
type : "POST",
data: formDataToUpload,
url : $('#updateProfilePictureLink').val(),
contentType:false,
processData:false,
cache:false,
dataType:"json",
success : function(response) {
$('#profilePicture').attr('src', result);
alert(response);
},
error : function (response) {
alert("error !");
}
});
I was thinking maybe "Simulate" a file upload in JS from the base64 using VichUploader formType input field, but I want to know if there are simpler ways.
Thanks
I managed to work around it thanks to Ronnie Hint.
You have to :
use JS FormData
put the blob inside
retrieve it in Symfony controller as an image
save it as is
But you have to implement serializable on your image's entity (serialize and unserialize all fields, unless it will break your other features).
Here is the working code sample :
// JS
$( "#cropSave" ).click(function() {
alert("click !");
basic.croppie('result','blob'
).then(function (result) {
var fd = new FormData();
//Third parameter is the blob name
fd.append('data',
result,$('#userId').val()+"."+result.type.split("/")[1]);
$.ajax({
type: 'POST',
url : $('#updateProfilePictureLink').val(),
data: fd,
processData: false,
contentType: false
}).done(function(data) {
// your things
});
// PHP
// Controller
try {
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$user->setImageFile($request->files->get('data'));
$entityManager->flush();
}
catch (exception $e) {
}
// Entity
class User implements UserInterface, \Serializable
{
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->profilePicture,
$this->email,
$this->password
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->profilePicture,
$this->email,
$this->password
) = unserialize($serialized);
}

php javascript download .gz file ajax

In my project I am using Symfony 3 + Filesaver.js and I need to download a .gz file. I do ajax request to my server with the following code:
function requestAjax(json_data) {
var request = $.ajax({
url: '/ajax'
, method: 'post'
, data: json_data
});
return request;
}
var json_text = {'type': 'download_file'};
var request = requestAjax(json_text);
request.done(function (response) {
var blob = new Blob(
[response], {
type: "text/plain;charset=" + document.characterSet});
saveAs(blob, 'filename.gz');
});
On php side I do the following:
$myfile = '/opt/myfile.gz';
$fp = fopen($myfile, "rb");
$response = base64_encode(fread($fp, filesize($myfile)));
fclose($fp);
return new Response($response);
But when I try to open my downloaded file, I get an error that the file is broken and cannot be read (still I can read it on my server and I know that the file is ok). So the question is how to download a .gz file with an ajax call in php + javascript. Thank you.

Having Issue On Uploading Loaded Image by jQuery Ajax on Server

I am trying to save a loaded image on Server Using jQuery,Ajax and PHP.
Here is the code I have for Ajax part:
<script>
$(function () {
$("#uploadimage").on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
var imgloader = $.ajax({
type: "POST",
url: "imgLoader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formData);
}
});
imgloader.fail(function () {
console.log('Error');
});
imgloader.done(function (data) {
$('#res').text(data);
});
});
});
</script>
and I have this PHP on imgLoader.php
<?php
if (isset($_FILES["file"]["type"])) {
$file = $_FILES['file']['tmp_name'];
$newloc = "newupload/" . $_FILES['file']['name'];
move_uploaded_file($file, $newloc);
} else {
echo 'There is Something Wrong?!';
}
?>
but I am getting the
There is Something Wrong?!
on the page without uploading the image on server. Can you please let me know what I am doing wrong? (I know this is not a secure and safe way to upload image to server, but please be informed that I am trying to lean the whole process of uploading without validation, sanitizing or filtering)
Thanks
AJAX doesn't do file uploads. It's not designed for that. For uploading files without page refreshing you will have to use any jquery ajax plugin.For e.g.
http://www.malsup.com/jquery/form/
This problem is already discussed in following link:
PHP and Ajax file upload - Can't get the tmp_name with $_FILES

AJAX Codeigniter - You did not select a file to upload(error)- How to pass the file through AJAX

I am trying to upload images via an AJAX call and Codeigniter:
My View:
<?php echo form_open_multipart('upload/do_upload'); ?>
<input type="file" name="userfile" id="userfile" size="20" />
<br />
<input type="submit" value="upload" id="upload_file_1" />
</form>
My Ajax Call:
$(document).ready(function(){
$(function() {
$('#upload_file_1').click(function(e) {
e.preventDefault();
var filename = $("#userfile").val();
$.ajax({
url :'index.php/upload/do_upload',
secureuri :false,
fileElementId: 'userfile',
dataType : 'json',
type : 'POST',
done : function (data)
{
alert(data);
}
});
});
});
});
and my controller:
class Upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$this->load->view('upload_form', array('error' => ' '));
}
function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '10240';
$config['max_height'] = '7680';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
echo "error!";
echo "<pre>";
print_r($error);
echo "<pre/>";
} else {
echo "done!";
}
}
}
but it gives me an error saying : "You did not select a file to upload. "; without AJAX it works fine, probably my AJAX call is not right! Could you please let me know if I am doing something wrong?
Thanks
In my very recent project i used below code to upload files with formdata asynchronously using jquery ajax,
However i was not able to upload files with success: function() of jQuery so i used complete to process server response. You can try with success:function().
You will receive your data in $_Post & file in $_FILES variable.
If only want to upload files. change it like wise.
Hope this will help you.
Also look at this tutorial:http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
function frm_submit(){
var form = new FormData(document.getElementById('frmSample')); //frmSample is form id
var file = document.getElementById('userfile').files[0]; //userfile file tag id
if (file) {
form.append('userfile', file);
}
$.ajax({
url: 'path/to/upload/script',
type: 'POST',
xhr: function() { // custom xhr
//progressHandlingFunction to hangle file progress
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: form,
cache: false,
contentType: false, //must
processData: false, //must
complete: function(XMLHttpRequest) {
var data = JSON.parse(XMLHttpRequest.responseText);
console.log(data);
console.log('complete');
},
error: function() {
console.log('error');
}
}).done(function() {
console.log('Done Sending messages');
}).fail(function() {
console.log('message sending failed');
});
}//function frm_submit ends here
i used this javascript library
https://github.com/blueimp/jQuery-File-Upload
and got file uploading working with ajax - drag/drop + progress bars, and returns the appropriate file icon or image thumbnail that could be downloaded straight away. it was quite difficult to get it fully working and abstracted so the same routine handled multiple types of uploads each with their own restrictions.
the link will give some basic example code, it is worth a look.
pete

Categories

Resources