TCPDF Progress Bar - php

I am using php and TCPDF to generate a custom PDF file from several MySQL queries. Once the user clicks the "Generate PDF" button a new tab opens and the PDF process starts. It takes, on average, about 10 seconds to build the PDF. Once the file is ready the browser closes the blank page and displays the save as dialog window.
I'd like to display some type of message to the user while the PDF is creating. I am somewhat of a noob when it comes to AJAX/JQUERY, but have tried to implement several solutions without success.
Things to note:
The backend is Joomla!
Using $pdf->Output('example.pdf','D') to generate the pdf
Using ob_end_clean prior to $pdf-Output to avoid the "TCPDF: Data already output" error.
I have tried the method that adds a <div> to the end of my page as well as some jQuery/CSS that would show an animated gif while the page is loading. It did not work, and I somehow get the feeling this is either caused by the ob_end_clean or the Joomla! framework.

1) for progress bar you must run the script via ajax
2)you have pdf page count...on each page creating you can change progress bar value
3)you must use php output control function for each pages of pdf created
php have a list of good function for this
i dont see your code but you must do some thing like this
$i = 1;
while($i< PDF_PAGE_COUNT){
ob_start();
pdf_create_page($i);
echo $i/PDF_PAGE_COUNT;
ob_flush();
flush();
$i++;
}
p.s : for better answer please paste your code here!

$(document).ready(function(){
$("#PDF").click(function(){
/*-------------- validate filters -------------------------------*/
if(!(validarFecha(fecha_ymd(rj.Get('#TxtFechaIni').value())))){Warn2.show();return false; }
if(!(validarFecha(fecha_ymd(rj.Get('#TxtFechaFin').value())))){Warn3.show();return false; }
if(Date.parse(fecha_ymd(rj.Get('#TxtFechaIni').value()))>=Date.parse(fecha_ymd(rj.Get('#TxtFechaFin').value()))){Warn.show();return false; }
/* is alll right */
else {
/* show a message while generating report*/
WinSnd.Message({type:'info', title:'generating report', value:'Please, wait ...', buttons:' '}).show();
/* url with params to send */
var url="report.php?&slash="+'<?php echo(isset($_POST['slash'])?#$_POST['slash']:#$_GET['slash']);?>'+"&module="+'<?php echo (isset($_POST['module'])?#$_POST['module']:#$_GET['module']);?>'
+"&TxtCheck=excel"
+"&TxtFechaIni="+rj.Get('#TxtFechaIni').value()
+"&TxtFechaFin="+rj.Get('#TxtFechaFin').value()
+"&LkpTdoc="+rj.Get('#LkpTdoc').value();
var filename = <?php echo '"'.$gSave.'"';?>; /* name for report, i set*/
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
WinSnd.hide(); /* hide message */
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response es un blob file
a.target = '_blank';
a.download = filename; // file name
a.style.display = 'none';
document.body.appendChild(a);
a.click(); // action
delete a; //
};
xhr.open('GET', url);
xhr.send();
}// fin validaciones
});//fin function
});// fin

Related

Download file after 10 seconds

I have created a download page that has a link to a file, I would like the file to download automatically after 10 seconds but am unsure of how to do this. The link to the file is stored in a cookie and is accessed on the download page and stored in a $file variable.
The link to the file will be similar to this:
https://cloud1.taccess.co.uk/cloud/uploads/eed376ad76d1f74b597aa2e21121f7e6tantami_cloud_file_580a40c1eff3af7484ef592c10bff10047b373cdc5dfd.pptx?AWSAccessKeyId=AKIAJ56YO6753B2RUT2Q&Expires=1477473886&Signature=mF6Zy1Mqo3HM5g%2B4cSePaXF9vM8%3D
This points to the file and includes the required permissions for the file to be downloaded. So in short, I am looking for a way for this link to be opened after 10 seconds so that the file can be downloaded.
Your tag is PHP. So I assume you want to add some delay for download, I think this
will help you
$filename = "your filename";
header("content-type:application/any specific header"); // set the header
// your content
sleep(10) // will add delay for 10 sec
header("Content-Disposition: attachment; filename=$file_name"); // will download your file
in javascript you could do like this
use heroku api to bring the page
<div id="hidden" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function(){
// var text = 'your url';
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'https://login.yahoo.com/', // like yahoo
function (response) {
var res = response;
$('#hidden').append(res);
});
});
after your page is placed inside hidden div then you could do something like this
setTimeout(function(){
$('#hidden').show();// or fade, css display however you'd like.
}, 1000);
});

Can't retrieve variable from php

PHP FILE:
<?php
#Communication with the API
require_once 'api.php';
$cloudkey = new CloudKey($user_id, $api_key);
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
//Deleted Code: putting the uploaded files in my server.
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
$video_file = "/home/george/public_html/q/";
$video_file = $video_file . $NewFileName;
#Sending the video from my server to the cloud server
$res = $cloudkey->file->upload_file($video_file);
#The cloud server will create a link
$source_url = $res->url;
#The cloud server will convert the video very fastly
while(1) {
#Deleted Code: Conversion
if ($asset->status == 'ready') {
# A lot of code. It will convert the videos here and if it succeeds it will stop.
break;
# If the conversion fails, display error
} else if ($asset->status == 'error') {
echo "Error while transcoding the media\n";
}
sleep(1);
}
# Getting the URL of a thumbnail
echo $thumb = $cloudkey->media->get_stream_url(array('id' => $media_id, 'asset_name' => 'jpeg_thumbnail_source'));
}else{
die('error uploading File!');
}
}
else
{
die('Something went wrong!');
}
?>
HTML FILE:
{literal}
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
//function after succesful file upload (when server response)
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
}
//progress bar function
function OnProgress(event, position, total, percentComplete)
{
//DOES NOT INTEREST YOU
});
</script>
{/literal}
<div id="output"></div>
I am using smarty template engine. I have an html upload form that will communicate with a php file progressupload.php where the php file will convert the video (using API services) and brings back a response when it finishes.
When the user uploads the video file, ajax will take over show the percentage (in html), and it will send the file to progressupload.php and when the progressupload.php finishes the conversion it will output everything echoed in the php by simply putting this in the html file (I don't know why): <div id="output"></div>.
WHAT I WANT:
When progressupload.php finishes the conversion, it will generate a thumbnail (screenshot) and store its link in $thumb. I want to retrieve $thumb and show it to the user using jquery.
Now if you look at the HTML Code, afterSuccess() is the function where I want to show the thumbnail to the user:
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO SHOW THE THUMBNAIL HERE.
}
I deleted a lot of unnecessary code that could've distracted you. Remember that I am using smarty template engine, my html file does not end with .php, I cannot echo the variable directly. How can I retrieve the php variable and put it in a jquery method after the variable is created.
I have a suspicion that if you retrieve the variable directly on page load, it will not succeed in getting $thumb since the link needs time to be created (uploading, conversion). How can I retrieve that $thumb?
Assuming that you are using jQuery.ajax();
First parameter in the $.ajax 'success' callback is what returned from the server side.
function afterSuccess( response /** this is what returned from your server **/ )
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
console.log(response); // here you can access your $thumbnail
// below code is untested but it should work
// $("#output").html("<img src='"+response+"' class='thumbnail' />");
}

JQuery Ajax Calls -- Intermittent image display issues (Chrome & FF) (some PHP and MySQL)

I use JQuery to pull form data and send an XMLHttpRequest(); I open the request using the POST method. The image and supplementary data are passed to a PHP script that handles, resizes, and saves it to the server. The file name and location of the image are updated in the relevant fields in a MySQL database. On the uploadComplete(evt) I attempt to display the newly uploaded image by calling .load() to populate a div.
80% of the time, the image displays correctly when the content is loaded into the div. 20% of the time, the image is displayed as if the link provided were a broken link. However, if I refresh the page, the image is displayed correctly.
Why does the image sometimes show as a broken link?
How do I stop it from doing this?
* EDIT
function loadFile()
{
var fileURL = $( "#url" ).val();
if(fileURL == "")
{
// Retrieve the FileList object from the referenced element ID
var myFileList = document.getElementById('upload_file').files;
// Grab the first File Object from the FileList
var myFile = myFileList[0];
// Set some variables containing the three attributes of the file
var myFileName = myFile.name;
var myFileSize = myFile.size;
var myFileType = myFile.type;
// Let's upload the complete file object
imageUpdate(myFile);
}
else
{
var newinfo = new Array();
newinfo[0] = "URL";
newinfo[1] = fileURL;
imageUpdate(newinfo);
}
}
function imageUpdate(newinfo)
{
var formData = new FormData(); // data object
// extra
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
formData.append("stylistID", stylistID);
// IF URL
if ( newinfo[0] == "URL" ){
formData.append("type", "URL");
formData.append("url", newinfo[1]);
}
// IF LOCAL FILE
else
{
formData.append("type", "FILE");
// Append our file to the formData object
// Notice the first argument "file" and keep it in mind
formData.append('my_uploaded_file', newinfo);
}
// Create our XMLHttpRequest Object
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
// Open our connection using the POST method
xhr.open("POST", "u/stylist_avatar.php", true);
// Request headers
//xhr.setRequestHeader("Content-Type", formData.files[0].type);
// Send the file
xhr.send(formData);
}
// While xhr is in progress
function updateProgress(oEvent)
{
if (evt.lengthComputable)
{
//var progressBar = document.getElementById("progressBar");
//var percentComplete = oEvent.loaded / oEvent.total;
//progressBar.value = percentComplete;
}
else
{
// unable to compute progress information since the total size is unkown
}
}
// onComplete
function uploadComplete(evt) {
//alert("The transfer is complete.");
resetForm($('#uploadImageForm'));
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
$('#uploadImageModal').modal('toggle');
// Reload right div
$( "#editStylistRight" ).load( "u/stylist_lookup.php", {stylistID: stylistID}, function (){});
// Reload stylist list
var index = 0;
var numRecords = 10;
$( "#stylistTable" ).load( "u/stylist_lookuptable.php", {start: index, end: numRecords}, function (){});
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
It seems that you are trying to show the new image before the PHP script in fact create and save the new image.
Instead of calling the javascript function that loads the new image on the "uploadComplete", use the "success" param (if you are using jQuery $.ajax function) that call the function that loads the new image.
The "success" function is called only when the server finish processing the request (when the PHP script finish editing and saving the image) and not when the new image params were succesfully sent to the server.
This happens because of image cache,force browser to fetch image evrytime.
use this in uploadcomplete event
var timestamp = new Date();
timestamp = timestamp.getTime();
imageurl+'?t='+timestamp;

$.get function not running in Chrome but working in IE and FireFox

I'm working on a site that uses php POST to upload files to a server and i'm trying to add a progress bar to the uploads.
I followed this guide:
http://www.ultramegatech.com/2010/10/create-an-upload-progress-bar-with-php-and-jquery/
It works great in ie and firefox. But the progressbar never updates in chrome.
This function gets called with a timeout of "500".
function updateProgress(id) {
var time = new Date().getTime();
// Make a GET request to the server
// Pass our upload identifier as a parameter
// Also pass current time to prevent caching
$.get('progressbar.php', { uid: id, t: time }, function (data) {
// Get the output as an integer
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
var div = document.getElementById('statusfield');
div.innerHTML = progress + '%';
// Determine if upload has started
started = progress < 100;
// If we aren't done or started, update again
updateProgress(id);
}
if (progress > 99) {
var div = document.getElementById('statusfield');
div.innerHTML = 'Komprimerar fil...';
}
// Update the progress bar percentage
// But only if we have started
started && pbar.progressbar('value', progress);
});
}
This function calls the .php file "progressbar.php" which passes the upload progress back as a percentage number.
progressbar.php:
<?php
if (isset($_GET['uid'])) {
// Fetch the upload progress data
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
// Calculate the current percentage
echo round($status['bytes_uploaded']/$status['bytes_total']*100);
}
else {
// If there is no data, assume it's done
echo 100;
}
}
?>
I have tested the code in chrome and the function "updateProgress" gets called. But it never gets past the:
$.get('progressbar.php', { uid: id, t: time }, function
Does anyone have any clue on what could be wrong?
Thanks!
In chrome go to dev tools (Options -> Tools -> Developer tools) and look at the network panel. Once the $.get method is called you will see your request and the result - you can see if it fails (for example if a 404 happens) so maybe chrome doesn't set the address as it should or if the sent data / return data isn't ok.

HTML5 drag and drop question

I'm trying to implement HTML5 drag and drop to upload a file. When the file is dropped, I want to call the php file to handle the dropped file. How can I call the php file and access the dragged file in php file. Also, I want to send the success or error message back from php file.
I'm unable to figure out how can I post the file to php and get the response from there.
My code so far is:
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
handleFiles(files);
}
function handleFiles(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = uploadFile; //main function
reader.onloadend = uploadComplete;
reader.readAsDataURL(file);
}
function uploadFile(evt)
{
//call upload.php
//get success msg or error msg
//alert(success) or alert(error)
}
Here's example upload.php file:
<?php
$dropped_file //how to get the file
if (filesize($dropped_file) > 1024)
{
echo "size error" //how to send this error
}
else
{
echo "success" //how to send this success msg.
}
?>
This should help - http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/
You can use jQuery, upon the drop callback perform an AJAX call.
$("body").droppable({
accept: "img", //Your element type goes here e.g. img
drop: function(event, ui){
//Perform an AJAX call here. You can access the current dropped item through
//ui.draggable
}
)}
Use jQuery UI will give you the ability to drag and drop in the most easy way

Categories