I'm using a customized example of plupload, where
one or more files are first uploaded to an Amazon S3 bucket, and
then file info + user-entered data (e.g. description) is POSTed
via ajax to my controller action in a loop.
This controller action then verifies that the file was upload to the S3 bucket and then saves the info into the database, returning a success or failure to the ajax call.
I use the 'UploadComplete' event to check for any upload errors, and if there are none, perform the actual POSTs in a loop.
What I'd like to do is wait until the entire loop has finished processing and then display the confirmation message (all success, all failed, mix of both) accordingly.
Current code:
uploader.bind('UploadComplete', function (up, files) {
var errorsPresent = false;
var errors = '';
// re-enable buttons
$('div.plupload_buttons a').removeClass('disabled');
$.each(uploader.files, function (i, file) {
if (errorDescArray.hasOwnProperty(file.id)) {
errorsPresent = true;
errors += errorDescArray[file.id] + '<br />';
}
else if (file.status = plupload.DONE) {
var jqXhr = $.post('/documents/add', {
'__RequestVerificationToken': $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(),
'filename': file.name,
'size': file.size,
'location': $('#' + file.id + '_location').val(),
'description': $('#filedesc_text_' + file.id).text()
}).error(function (response) {
errorsPresent = true;
errors += response.responseText + '<br />';
});
}
});
//
if (errorsPresent) {
$('#uploadErrors').html('<div data-alert="alert" class="alert-message block-message fade in error">×<p>' + errors + '</p></div>');
}
else {
// set confirmation message
var message = files.length + ' file(s) were successfully uploaded.';
// clear file list
$('ul.plupload_filelist').html('');
// remove files from list
uploader.splice();
// hide modal
$('#upload-modal').modal('hide');
// show confirmation
$('#flashMessage').html('<div data-alert="alert" class="alert-message block-message fade in success">×<p>' + message + '</p></div>');
}
});
The above is obviously flawed in that the second half of the snippet doesn't really wait for the POSTs to complete, with the result that the success confirmation is displayed even if POST has an error response.
So my question is this: How do I perform an ajax post in a loop (unless there's a better way) and process the confirmation message after the loop has finished processing?
Related
i'm using resumable js to upload video on JWPlayer in laravel wepapp. when i upload video. it uploads only first chunk of video on jwp dashboard then return below error in network tab.
a:4:{s:6:"status";s:5:"error";s:7:"message";s:72:"Uploads for the media files with the status `processing` are not allowed";s:4:"code";s:16:"PermissionDenied";s:5:"title";s:17:"Permission Denied";}
since last two i'm looking for solution. see below my resumable js code. i passed 1mb chunk on jwp server to store. but after first chunk it says "Uploads for the media files with the status processing are not allowed" as i mentioned full error message above.
var $ = window.$; // use the global jQuery instance
var $fileUpload = $('#resumable-browse');
var $fileUploadDrop = $('#resumable-drop');
var $uploadList = $("#file-upload-list");
if ($fileUpload.length > 0 && $fileUploadDrop.length > 0) {
console.log($fileUpload.data('url'));
var resumable = new Resumable({
// Use chunk size that is smaller than your maximum limit due a resumable issue
// https://github.com/23/resumable.js/issues/51
chunkSize: 1 * 1024 * 1024,
// 1MB
method: "POST",
simultaneousUploads: 1,
testChunks: false,
throttleProgressCallbacks: 1,
// Get the url from data-url tag
target: $fileUpload.data('url'),
headers: {
"X-Session-Id":$("#jwToken").val(),
},
// Append token to the request - required for web routes
query: {
_token: $('input[name=_token]').val()
}
}); // Resumable.js isn't supported, fall back on a different method
if (!resumable.support) {
$('#resumable-error').show();
} else {
// Show a place for dropping/selecting files
$fileUploadDrop.show();
resumable.assignDrop($fileUpload[0]);
resumable.assignBrowse($fileUploadDrop[0]); // Handle file add event
resumable.on('fileAdded', function (file) {
// Show progress pabr
$uploadList.show(); // Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show(); // Add the file to the list
$uploadList.append('<li class="resumable-file-' + file.uniqueIdentifier + '">Processing <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-name').html(file.fileName); // Actually start the upload
resumable.upload();
});
resumable.on('fileSuccess', function (file, message) {
// Reflect that the file upload has completed
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(completed)');
});
resumable.on('fileError', function (file, message) {
// Reflect that the file upload has resulted in error
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(file could not be uploaded: ' + message + ')');
});
resumable.on('fileProgress', function (file) {
// Handle progress for both the file and the overall upload
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html(Math.floor(file.progress() * 100) + '%');
$('.progress-bar').css({
width: Math.floor(resumable.progress() * 100) + '%'
});
});
}
}
/***/ }),
I'd make sure when you created the video that you specified the multipart upload method.
Also make sure the location you're trying to upload to is the one returned in the create call (it should be going to the /v1/videos/upload/resumable endpoint). This guide should give more details about the process.
I am trying to scrape http://www.snapdeal.com/offers/deal-of-the-day which loads JSON data using an AJAX call to below page:
json_url = http://www.snapdeal.com/json/getProductById?*
The code block I am using is below, I get the log message Waiting for AJAX request:, but not the Waiting for AJAX request:, instead waitForResource times out
casper.options.onResourceRequested = function (casper, requestData){
// loop through our AJAX urls
// create list of AJAX urls to track
var ajaxUrls = [json_url];
ajaxUrls.every(function(ajaxUrl){
// does this request match an AJAX url
if(requestData.url.indexOf(ajaxUrl) !== -1){
// it matches, so we'll wait for it to return (with 10s timeout)
//console.log("Waiting for AJAX request: " + requestData.url);
// print_object(requestData);
casper.waitForResource(requestData.url, function(){
console.log("AJAX request returned: " + requestData.url);
}, function(){
console.log("AJAX request didn't return after wait period: " + requestData.url)
}, 10000);
}
});
}
To further debug, I logged events and the resource at url json_url was successfully received, but not sure why waitForResource times out.
casper.on('resource.received', function(resource) {
if (resource.url.indexOf('http://www.snapdeal.com/json/getProductById') != -1){
casper.echo('resource.received: ' + resource.url);
}
});
Log after run:
Waiting for AJAX request: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,1775140628,1822452791,439536 ,Range,2042952975,1472100667,899358889,643129681532,668235859588,&lang=en
resource.received: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,1775140628,1822452791,439536,Range, 2042952975,1472100667,899358889,643129681532,668235859588,&lang=en
resource.received: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,1775140628,1822452791,439536,Range, 2042952975,1472100667,899358889,643129681532,668235859588,&lang=en
AJAX request didn't return after wait period: http://www.snapdeal.com/json/getProductById?pogIds=671556289429,649272180,60998,685755068805,677649317861,1239888775,661402031482,636966047361,17751406 28,1822452791,439536,Range,2042952975,1472100667,899358889,643129681532,668235859588,&lang=en Got page No Offeres Found thestartin: ~/Appli
What you need is:
casper.waitForSelector()
or
casper.waitFor(function() {
// test here something that return true when the page is loaded
})
I'm doing direct upload to S3 using html form and ajax. It's working good, files get uploaded. My problem is that progress events arrive too quickly. Like all of them up to 99.9% are fired immediately at the start of the upload.
var fd = new FormData();
// put data from the form to FormData object
$.each( $('#upload-form').serializeArray(), function(i, field) {
fd.append(field.name, field.value);
});
// add selected filename to the form data
var file = document.getElementById('path-to-file').files[0];
fd.append("file", file);
var xhr = getXmlHttpRequest(); // cross-browser implementation
xhr.upload.addEventListener("progress", function(e) {
console.log(e.loaded + "/" + e.total);
});
xhr.open('POST', 'http://mybucket.s3.amazonaws.com/', true);
xhr.send(fd);
also tried this way
xhr.upload.onprogress = function(evt)
{
if (evt.lengthComputable)
{
console.log(e.loaded + "/" + e.total);
}
};
Browser log looks like this:
[22:54:47.245] POST http://mybucket.s3.amazonaws.com/
[22:54:47.287] 359865/5680475
[22:54:47.330] 1408441/5680475
[22:54:47.408] 2751929/5680475
[22:54:47.449] 3964345/5680475
[22:54:47.509] 5668281/5680475
and then nothing for the time it actually takes to upload a 5M file.
If browser info is relevant, I have Firefox 20.0.1
I am using Uploadify to upload image in php(codeigniter). Tested with the sample php file that come with the uploadify package. It works. However, I can't get onUploadError triggered. The sample php code has:
if (in_array($file_ext,$fileTypes)) {
$newFileName = mt_rand() . time() . '.' . $file_ext;
$targetFile = rtrim($targetPath,'/') . '/' . $newFileName;
move_uploaded_file($tempFile,$targetFile);
echo $newFileName;
} else {
echo 'Invalid file type.';
}
js is very simple as following:
$('#file_upload').uploadify({
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.jpeg; *.png',
'swf' : '/static/uploadify/uploadify.swf',
'uploader' : '/static/uploadify/uploadify.php',
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
console.log('The file ' + file.name + ' errorCode ' + errorCode + ' errorMsg ' + errorMsg + ' errorString ' + errorString);
},
'onUploadSuccess' : function(file, data, response) {
console.log(data);
}
});
when the Invalid file type. is echoed to the frontend. the onUploadSuccess is triggered instead of onUploadError. It seems odd to me that there is no indicator to stell uploadify there is an error from php.
the only way that triggers onUploadError is to set a non 200 http header before echoing. however, onUploadError function arguments errorCode, errorMsg, errorString are the http code and the echo content(error message) is lost.
UPDATES
I modified the question title so it speaks the real problem I was trying to solve. And I have since found the solution.
I finally got sometime to tackle this problem and here are my steps to solve it.
first, the problem of onUploadError is not fired is because the file has been uploaded successfully
second, uploadify queue limit and upload limit are updated accordingly upon successful upload regardless of detection of wrong image dimension from the backend.
So the solution is that my backend checks image dimension and responds with a json data with error message which shown to user. also reset uploadify, really it is swfupload, variable successful_uploads. that makes sure the queuelimit or upload limit not messed up. sample code:
'onUploadSuccess' : function(file, data, response) {
var obj = eval('(' + data + ')');
if ( obj.success ) { alert('uploaded') }
else {
var stats = this.getStats();
this.setStats({successful_uploads: stats.successful_uploads - 1});
}
}
see swfupload setStats method http://demo.swfupload.org/Documentation/#setStats
I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
type : "POST",
url : "/usermanageajax/",
data : 'key=' + key_value,
success : function (data) {
var element = users.salary[users.salary.length -1];
var hrs = users.hours[users.hours.length -1];
var html = "<span title=\"" + users.name + "\">Name \"" + users.desc(0,50) + "...\" "+ "has " + element + " of "+ hrs + "</span>";
// alert('*');
$('#title').html(html);
chart_s = draw_chart(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?
The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler. You can also check for success there.