Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i retrieve the progress of a native html form submission?

I'm doing some front-end stuff for a Rails app and I don't get to mess with the backend architecture. Basically, I'm supposed to allow users to upload a file and make that submission essentially go straight to Amazon through a form handled by CarrierWave. If you've ever tried to do this same thing with ajax, you'll know it's virtually impossible.

That puts me here: I need to be able to call .submit() on an html form element and then hook into the progress of the upload as if I were listening for the "progress" event on an XMLHttpRequest.

Forgive me for not showing tons of code. I'm really just looking for two very simple things.

  1. Is it possible to trap the form's native progress event?
  2. If so, what's the basic technique? Is it something simple like form.addEventListener('progress', function () {...})? (<- That doesn't work, by the way.)
like image 872
rescuecreative Avatar asked Dec 30 '13 17:12

rescuecreative


1 Answers

I don't think you can get progress on the upload on a standard form submit.

So I haven't tested this, but why not submit the form via AJAX? You can upload files with a FormData object, which can handle multipart requests for uploads.

Something like this might work:

// grab the form you want to submit.
var formElement = document.getElementById("myFormElement");

// make an xhr object
var request = new XMLHttpRequest();

// track progress
request.upload.addEventListener('progress', progressHandler, false);

// setup request method and url
request.open("POST", formElement.action);

// send the request
request.send(new FormData(formElement));

You would have to listen for the server response and do what it tells you, redirect or handle failures or whatever. But I think it should work. The server you are submitting to probably doesn't care if it's a xhr request or a standard browser request.

And it should work in all modern browsers.


See docs on FormData.

And here's a link to that details how to track progress on ajax uploads.

like image 123
Alex Wayne Avatar answered Oct 20 '22 16:10

Alex Wayne