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.