I found a bug while using uploadify. When I user the scriptData attribute to pass post information to the script the loader does not work. The script is actually called and the items are uploaded but the loader hangs on 0 %. When you user multiple files it will hang on the first one sometimes on 95% and mostly on 0%.
It looks as tho the files arent uploaded but they are. This is very anoying though, seeing that the user will think their files arent uploaded and wait on the screen. I tried to work around this by just using GET information and putting my extra variables into the actual url in the script: attribute. This also results in the same problem. A simple note is that I am using CodeIgniter for this project so this could be a problem. It would really be helpful if this was fixed but dont know if its gonna happen any time soon.
I checked this problem on multiple browsers and have the same issue. Has anyone here dealt with this. I used to like uploadify but Im begging to start looking for something else
I had this problem, too, and it drove me crazy. It turns out that the script that you're using to handle the upload has to output something - anything - before uploadify will continue. So in your 'script', like upload.php below, make the last line of the script output something at the bottom of the script - even something simple like echo "done";. This will let uploadify know that the script is finished so it can continue.
$('#file_upload').uploadify({
'uploader' : '/js/jquery/uploadify/uploadify.swf',
'script' : '/distributed/ajax/upload.php',
'cancelImg' : '/js/jquery/uploadify/cancel.png',
'folder' : '/distributed/files',
'auto' : true,
'scriptData': { 'request_no':req_no },
'onComplete': function(evt, ID, fileObj, response, data) {
alert("Finished!");
}
}
});
Related
I need advice on my ajax progress bar while executing a long PHP script treating pictures.
I know there are plenty of questions on stackoverflow already like
Show progress for long running PHP script
or JQuery ajax progress via xhr
or update progress bar using ajax request seconds)
Most of the examples I see are using the file size to calculate the progress.
But in my case I would like to calculate percentage based on images_treated / total_images.
So I still can't make this work as I want.
In JS bellow I commented the not working progress function I took from another question and dataType: 'json' for tests but I would prefer if I can still use a JSON return.
Questions
The console.log() will only log once - when the full script is done. Am I doing it wrong?
What should I write to replace the comment?
in some answers, the PHP headers are set to header('Content-Type: application/octet-stream'); is it mandatory or just nicer?
Javascript:
$.ajax(
{
type: 'GET',
// dataType: 'json',
url: formAction,
data: 'addImagesToArticle',
cache: false,
xhr: function()
{
var xhr = new window.XMLHttpRequest();
// Download progress.
xhr.addEventListener("progress", function(e)
{
console.log(e);
// I saw this piece of code from another question it is supposed to work... Maybe my PHP?
/*var lines = e.currentTarget.response.split("\n");
var progress = lines.length ? lines[lines.length-1] : 0;
$('#progress').text(progress);*/
}, false);
return xhr;
}
});
My PHP is quite big so I just explain quickly: in the loop on pics I have variables $images_treated and $total_images. After the loop, a summary is returned to JS via JSON in an object like {error: bool, message: string, ...} so if there is a way to make the progress work without echoing but setting a JSON variable that would be perfect!
Thank you for your help!
[EDIT] to add context details.
I want to use this in an admin side, in an article edition with a WYSIWYG, I have dropzone taking care of my multiple images uploads.
then I see the preview of images while each image is put in temp folder on server. I can then remove some images if needed and once all images are definitive, i click a button that will process them for resizing 2 sizes and inject figure tags with img in the article WYSIWYG editor.
Waw I found a solution!
I am happy to discover that new thing I did not know about PHP and share with people who also don't know (in step 3 bellow)!
#riccardo was right talking about socket - which I don't know so well - but I did not need to go that far.
So I had multiple things to solve in my case before being able to get closer of my goal.
not using xhr.addEventListener("progress"... but a second ajax call in a timer: it will also be lighter-weight in resource consumption.
rather than using a timer like setInterval or setTimeout - as requests are async it may come in unwanted order - use a recursive call in callback of first call like:
function trackProgress()
{
$.getJSON('create-a-new-page.html', 'ajaxTrackProgress=1', function(response)
{
var progress = response.progress;
$('#progress').text(progress);
if (progress < 100) trackProgress();
});
}
then realize that my second script call is delayed by first script still running? yes. So the key here is session_write_close()!
I could dig in this way thanks to this good post:
https://stackoverflow.com/a/1430921/2012407
and I posted a very simple example here to reply to another question: https://stackoverflow.com/a/38334673/2012407
Thank you for all your help in comments guys, it led me to this solution. ;)
I've been using stackoverflow for months now as it really is the the most reliable resource I can think about. However, I now have my own question.
I'm working on a script that displays available courses in an HTML5 page using ajax after calling some php/MySQL interaction. I was using jQuery 1.4.1 (yeah... i know) and due to some interesting new plugins available, I updated to 1.10.2.
Now my page doesn't display the product of the PHP/SQL processing anymore, nor does the autoscroll work.
I did some search and didn't find any answer.
I was hoping you guys would see directly the incompatibility in my code, or the usage of a too old syntax.
Trigger :
<a class="internal-link" href="#" onclick="goToByScroll('reanimation');"></a>
Script :
function goToByScroll(id){
$.ajax({
type: "POST",
url: "kernel/appel-tableaux-ajax.php",
dataType: "script",
data:{type_cours : id},
success: function(array){
var objet = JSON.parse(array);
var message = objet["message"];
var nombre = objet["nombre"];
$("#conteneur-tableaux").html(message);
$("#nombre-cours").html(nombre);
if(nombre==0)
{
$("#titre-section-tableaux").css("color","darkred");
}else{
$("#titre-section-tableaux").css("color","darkgreen");
}
$('html,body').animate({scrollTop: $("#section-tableaux").offset().top},'slow');
}
});
}
PHP code (I erased stuff where mistakes are less probable) :
ob_start(); // I want to catch all the 'echos' to insert them in an array.
while ($donnees = $reponse->fetch())
{
// Lots of Date comparison stuff and many ECHOS.
}
$out = utf8_encode(ob_get_contents()); // --- I put every echos inside the 'OUT' variable.
ob_end_clean();
// --- I want to send back 2 things to my script, some infos about the courses available, and the total number of available courses. So I create an array.
$output_final = array ("message" => $out, "nombre" => $compteur_cours);
echo json_encode($output_final);
?>
As you can see, I'm a beginner in Ajax and jQuery usage.
UPDATE :
Thanks a lot to all those who already helped.
I tried the debug tools in Chrome, the php generates exactly what it's supposed to do, which means that my ajax is able to call the PHP code placed in kernel/appel-tableau-ajax.php. The Console.log() placed in the success case doesn't display anything.
I'm adding a screenshot of the syntax errors that Chrome detected. If someone could help me to understand how to handle those errors it would be wonderful.
Link to the screenshot
Also, Safari's debugger says : SyntaxError: JSON Parse error: Unexpected identifier "object".
I can't believe all this worked on the old jQuery version...
Thanks a lot, I hope I'm not asking too much!
if your php code return json why the 'dataType' in your ajax is 'script'? try change it to json.
hope it will work! :)
I'm having some trouble with a function using jQuery post. The function is supposed to run itself several times and then stop, which it has done successfully in the past. What is happening now is that the first time it runs the function, the php script executes fine. When it tries to run itself again, I get a 404 error.
Here's the javascript function:
function ajax_call(senddata){
$.post("/script.php", senddata,
function(data) {
if(data.pointer != "done"){
setTimeout(ajax_call(data), 100);
}
}, "json");
}
The output of the php file is:
{"pointer": "1234"}
The error is occuring in a wordpress plugin I'm writing and displays as:
POST http://xxxxx.local/script.php 404 (Not Found) - load-scripts.php
As I said, the first time it works. The php file runs with no errors, so the file exists, and I'm calling it correctly in the function. It has worked in the past and I've reverted both scripts to a point in which I know it worked. If anyone has any ideas as to what would be causing this, it would be greatly appreciated. Thank you.
I don't think there's anything wrong with your JS. What I would do is use firebug or F12 in IE to see what's going on over the network (network tab). Check the request and response detail and make sure everything makes sense.
After that I'd check the server logs to see if you can see anything about that 404'ing request.
I have seen all the upload progress bar plugins, widgets, etc. – they all suck. They're either too bulky with too much useless code or they don't work.
What I want to know is where I can read up on how to display an easy upload progress indicator. Most browsers have a status progress bar on them below, but it isn't very professional to use just that when dealing with clients.
How does the browser do it? I want to know the internals of how the browser works with for indicating the status of something uploading so that maybe I can make something using PHP & jquery.
Thanks.
Since you want to use PHP, I'd start with the uploadprogress extension (PHP doesn't, by default, give you any data about until the upload is completed; this extension provides such server-side functionality). Note that it requires PHP 5.2+ and can be picky about configuration options. Also see its commentary and demo and troubleshooting hints). A short overview available in PHP documentation comments.
Using the extension, you can get some stats on the upload; then you can poll the server through AJAX and update some sort of progress bar.
To be a bit more specific:
get an unique identifier for the form, and include it in a hidden field
the upload should run in an IFRAME - some browsers won't allow DOM updates to the same page that is running the upload
poll the server via AJAX (using the identifier to specify which upload you're interested in) and parse the result (IIRC, you'll get something like "bytes_uploaded => 123, content-length=> 1000")
update your progress bar (the way you display it is up to you, I use "x% done" plus a graphical bar)
redirect whole page when form uploaded OK
(Oh, and btw, check PHP's upload_max_filesize and post_max_size settings, as both limit the maximum upload size)
There is no reliable method to get the progress of a file upload using JavaScript. Support for the XMLHttpRequest upload.onprogress event is missing in many browsers, even with HTML5, you will inevitably need to turn to Flash, or another method of file upload.
After asking this question, I eventually settled on using plupload for my uploading needs.
Javascript/Ecmascript cannot mess with native browser functionalitys (which uses C/C++ mostly along with OS APIs which access TCP/UDP sockets.
To display a progressbar with JS you need serverfeedback. That can be accomplished by using a server polling like COMET for instance.
But at this point, it's never that accurate like the browser buildin progressbar. It will change maybe with HTML5 WebSockets.
To have an accurate result, you need a continuous connection. You can fake and gild the client-server request delay, but it's still there. I don't know exactly how Flash handles this issues, but I guess it also does not have connection-oriented stream (Correct me if I'm wrong here).
I know this isnt what you're looking for but I've been using plupload for uploads recently and it seems pretty good plus doesnt rely on flash or html5 exclusively
example:
the url is the proccessing page (php
file)
container = the parent div or form that that the upload button lives in (its really important to set this - there are some example of how you can attach things to certain actions that plupload does. for example below you can see i have attached uploader.start();to the uploader.start(); hook.
you should also be able to see how i've made a custom upload progress bar, by attaching to the upload progress hook
worth asking questions on the forum on the plupload site if you get stuck, they're good at answering them!
$(function(){
//plupload
var uploader = new plupload.Uploader({
runtimes : 'gears,html5,flash',
browse_button : 'pickfiles',
container : 'form_2',
max_file_size : '10mb',
url : '<?php echo SITE_ROOT ?>plupload/upload.php',
//resize : {width : 320, height : 240, quality : 90},
flash_swf_url : '<?php echo SITE_ROOT ?>plupload/js/plupload.flash.swf',
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
]
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
uploader.start();
});
uploader.bind('UploadProgress', function(up, file) {
if(file.percent < 100 && file.percent >= 1){
$('#progress_bar div').css('width', file.percent+'%');
}
else{
$('#progress_bar').fadeOut(600);
}
});
I am using Uploadify to enable my users to upload images via my web application.
The problem I am having is that every now and then (at what appears to be random) when the progress bar reaches 100% it 'hangs' and does nothing.
I was wondering if any developers familiar with uploadify may have any idea how to solve this? I am in desperate need of some help.
Here is my front-end code:
<javascript>
jQuery(document).ready(function() {
jQuery("#uploadify").uploadify({
'uploader' : 'javascripts/uploadify.swf',
'script' : 'upload-file2.php',
'cancelImg' : 'css/images/cancel.png',
'folder' : 'uploads/personal_images/' + profileOwner,
'queueID' : 'fileQueue',
'auto' : true,
'multi' : true,
'fileDesc' : 'Image files',
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'sizeLimit' : '2097152',
'onComplete': function(event, queueID, fileObj, response, data)
{
processPersonalImage(fileObj.name);
arrImgNames.push(fileObj.name);
showUploadedImages(true);
document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')";
},
'onAllComplete' : function()
{
completionMessage(arrFailedNames);
document.getElementById("displayImageButton").style.display = "inline";
document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')";
},
'onCancel' : function()
{
arrImgNames.push(fileObj.name);
arrFailedNames.push(fileObj.name);
showUploadedImages(false);
},
'onError' : function()
{
arrImgNames.push(fileObj.name);
arrFailedNames.push(fileObj.name);
showUploadedImages(false);
}
});
});
</javascript>
And server side:
if (!empty($_FILES))
{
//Get user ID from the file path for use later..
$userID = getIdFromFilePath($_REQUEST['folder'], 3);
$row = mysql_fetch_assoc(getRecentAlbum($userID, "photo_album_personal"));
$subFolderName = $row['pk'];
//Prepare target path / file..
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$subFolderName.'/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
//Move uploaded file from temp directory to new folder
move_uploaded_file($tempFile,$targetFile);
//Now add a record to DB to reflect this personal image..
if(file_exists($targetFile))
{
//add photo record to DB
$directFilePath = $_REQUEST['folder'] . '/'.$subFolderName.'/' . $_FILES['Filedata']['name'];
addPersonalPhotoRecordToDb($directFilePath, $row['pk']);
}
echo "1";
die(true);
}
thanks for any help!!
this seems like a php error.
I'd use Fiddler or a similar problem to view the php response or similar.
Check your php error logs, they might shed some light.
I had a similar problem some time ago with Uploadify (using ASP.Net MVC though) - but you will definitely find some useful info regarding the Uploadify event handling and behaviour in the answer posted! Its available here
I had the same problem.
Simply add echo "astlavista babi" to your uploadify script, this echo statement should be the last line, if you have conditional statement then echo should be placed as a last line within the conditional statement.
These are the steps I would take, in order:
1) Be 100% certain you are getting a 200 response from your server. If not, that is the problem
2) Use the latest and the greatest uplaodify and jquery
3) Check for JS errors (firebug console or browser JS debugger will work)
4) Upgrade your Flash player (if that solves it then you can require a higher version)
5) Put a debug statements in the uploadify source, specifically in the complete handler to be sure it gets called
6) If the progress is reaching 100% but the handler never gets called, I'm afraid the next step may be to dive into the actionscript and use the debugger or some trace statements to figure out where the error is. This can mean that there is a bug in calling the external interface function
7) If you make fixes, submit back to uploadify
Chreck your php.ini file for post_max_size parameter. It must be >= upload_max_filesize parameter. For more details see http://php.net/post-max-size.
For future reference: I had this problem when sending data to the upload script using "scriptData" and solved it by simply echoing "ok" in the upload script rather than sending back an empty document.
For those who are using Macs use HTTP Scoop to view the request as Firebug does not show it. More on HTTP Scoop from this blog.