0

I've been struggling with this for days. I need to be able to execute JavaScript code after a file form is submitted so I can do something with that file.

These are the approachs that I've already tried:

1) Call js.erb file through controller's action

routes.rb:

post 'workflows/:id/upload', to: 'workflows#upload_files', as: 'workflows_upload_files', defaults: { :format => 'js' }

controller (empty):

def upload_files
end

upload_files.js.erb:

console.log('Some log');

form:

<%= form_for(:printing_file, remote: true, html: { id: 'upload-form'}, url: workspace_workflows_upload_files_path(@workspace, workflow)) do |f| %>
  <%= f.file_field :file, multiple: true, name: 'workflow[printing_files][]', class: "printing-file-upload-field", onchange: "this.form.submit()" %>
<% end %>

I don't know why, but this produces a cross-origin error. When I solve it adding protect_from_forgery except: :upload_files then the js code is being rendered as plain text but not evaluated.

I've tried with adding this code on application.js but it didn't worked (a solution proposed on this question):

 $.ajaxSetup({  
    'beforeSend': function (xhr) {xhr.setRequestHeader('Content-Type', 'application/javascript');}  
 });

2) Handle input field change event

I've also tried the solution on this answer:

$(".printing-file-upload-field").change(function(){
  console.log(this.files);
});

The result: the event is fired, but I only got undefined.

3) Handle form complete event

I've also tried this answer.

$("#upload-form").bind('ajax:complete', function() {
  console.log('The form was submitted!');
});

The result: the event isn't triggered.

Community
  • 1
  • 1
fsinisi90
  • 873
  • 12
  • 36

2 Answers2

0

Could you try removing remote: true from the form_for ? http://guides.rubyonrails.org/form_helpers.html#dealing-with-ajax

Joel Blum
  • 6,319
  • 8
  • 37
  • 53
0

Finally I used a variant of the 2nd option: handle the input field change event.

The problem was that I was submitting the form, so I changed onchange='this.form.submit()' for onchange='readInputFile(this)' and it worked. Then I added this code to manipulate the file:

readInputFile = function(input_file_field) {
    if (input_file_field.files && input_file_field.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            doSomethingWithTheFile(e.target.result);
        }
        reader.readAsDataURL(input_file_field.files[0]);
    }
}

I also discovered that in the 3rd option the event wasn't triggered because it doesn't trigger when you submit the form "manually" with this.form.submit().

Hope this helps someone!

fsinisi90
  • 873
  • 12
  • 36