HTML5 drag and drop question - php

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

Related

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' />");
}

TCPDF Progress Bar

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

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;

Write jQuery variables to a file

I have used a jquery function to process a form which is given below.
$("#advertForm").submit(function(e)
{
var url=$(target).attr('title');
var imgname=$(target).attr('name');
var Form = { };
$.post('processAdvert.php', Form, function(data)
{
if(data == "Success")
{
setTimeout( function() { location=url }, 2500 );
return;
}
});
return false;
});
I need to write url and imgname to a text file. I know there is no way to write a file in jquery. Can I use any PHP function (fwrite) to write this variable into a file? How can I write this variable into a file?
Yes you can do that in some way. Send an ajax request to your php file. process your data, create a file, write some data using fput() method, Use force download class that will allow you to download the file at that moment. Ask if you have any confusion.

Event when video is done - Possible?

Is it possible to have a flash/html5 video on a webpage, and when the video is done, it will run a PHP script?
You'd have to do a check inside both the html5 player and the flash player to determine if the video has stopped playing and then you should be able to call a php script through several ways. Let's say you have a php file called 'test.php' then in html5 you'd do the following:
<script>
var video = document.getElementsByTagName('video')[0];
video.onended = function(e) {
$.post(
"test.php",
function(data) {
/*Do stuff here!*/
},
"json"
);
}
</script>
In flash it's a bit different and you could try doing something like the following in actionscript3:
stream.addEventListener(NetStatusEvent.NET_STATUS, statusChanged);
function statusChanged(stats:NetStatusEvent) {
if (stats.info.code == 'NetStream.Play.Stop') {
// create a new loadvars variable
var lv:LoadVars = new LoadVars();
lv.load("http://www.myurl.com/test.php");
// now define what you want to do with the loaded data:
lv.onLoad = function(){
/*Do stuff here!*/
};
}
}

Categories