I’m using the Plupload file uploader within a form. I want to customize it such that when the form is submitted, i.e. when the “Submit” button is clicked, the first thing that happens is the file uploading, followed by the submission of the form.
From what I can tell, and I might be wrong with this, but it seems that the call uploader.start() is an asynchronous function call. So at the moment, the uploading will begin and the form will submit before the files are uploaded. The problem is that I don’t have control over this function call.
I’ve recently read about the new release of jQuery 1.5 and the new Deferred Object and it seems like this has the potential to help me solve this problem. Is there a way to wait for the asynchronous function call to finish its work and then continue the execution of the code after the call. So I’m looking for something like the following pseudocode…
var uploader = $('#plupload_container').pluploadQueue();
$('#submitButton').click(function() {
// if there are files to be uploaded, do it
if (uploader.files.length > 0) {
// make the call and wait for the uploader to finish
uploader.start();
while ( the uploading is not done ) {
wait for the uploader to finish
}
// continue with submission
}
});
Is there a way to “wait” for uploader.start() to finish, essentially putting a pause on the click event handler, so that all the files can be uploaded first and then the rest of the click event handler can finish executing? I’ve tried the following but “done” is printed before the files are done uploading…
$.when(uploader.start()).then(function () {
console.log("done")
});
Another useful piece of information… I can bind certain events to this uploader object instance, such as “UploadProgress” or “UploadComplete”. Can I use the Deferred Object somehow to catch when the “UploadComplete” event fires, for example? Is there an AJAX-y way to do this?
Thanks.
Your problem is that although
uploader.startdoes something asynchronous for the code to work,uploader.starthas to return a jquery$.deferredobject.From the latest source on your uploader plugin:
So it doesn’t return a deferred object. Instead in the
uploadNextfunction there is this line of code:this.trigger("UploadComplete", files);So we simply have to bind to your uploader,
I’ve never used that plugin but this should work. Good luck.
If you must use deferreds then you can always something like this pseudocode: