Bjoernsen
Bjoernsen

Reputation: 2418

form_tag with remote: true does not make an ajax request

I have many different forms in my app, all of them are using remote: true. But one does not work correctly, because is does not use an ajax call.

Cleaned up, it looks like:

<%= form_tag(upload_file_ajax_path, remote: true, multipart: true) do %>
  <%= file_field_tag(:file) %>
  <%= submit_tag("upload") %>
<%end%>

The tag looks like:

<form accept-charset="UTF-8" action="/mycontroller/upload_file_ajax" data-remote="true" enctype="multipart/form-data" method="post">
  <input name="utf8" type="hidden" value="✓">
  <input name="authenticity_token" type="hidden" value="1234"></div>
  <input id="file" name="file" type="file">
  <input name="commit" type="submit" value="upload">
</form>

And the routes entry:

post "mycontroller/upload_file_ajax", as: "upload_file_ajax"

But checking the call in Chrome Dev Tools, the header says:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

and not like the other forms look like:

Accept:*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript

I added the js files to my layout

<%= stylesheet_link_tag    "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>

And even if I remove all my JS code out of the application.js file (except the //= require jquery...), the form is not working correctly.

What did I miss?

Upvotes: 17

Views: 11332

Answers (2)

Erez Rabih
Erez Rabih

Reputation: 15788

The problem you experience is due to the fact that files cannot be submitted by AJAX requests.

You can try to use Jquery Form plugin to upload files via AJAX request using the ajaxSubmit method provided by the plugin

Upvotes: 2

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

You can't use AJAX for file uploads. That is, normally.

There is an awesome gem, Remotipart, that adds this functionality to your remote forms though.

gem 'remotipart', '~> 1.0'

In application.js

//= require jquery.remotipart

Upvotes: 26

Related Questions