EzDevInfo.com

remotipart

NOTE! THIS REPO HAS BEEN MOVED. SEE THE README. Remotipart is a Ruby on Rails gem enabling remote multipart forms (AJAX style file uploads) with jQuery. remotipart | RubyGems.org | your community gem host

Submitting a form with file input using remotipart wraps a textarea to response

Using Ruby on Rails 4 and Ruby 2.

Here's my simple controller action. When validation fails I render the 'new' action and inject the contents of the view into the .ajax-target div.

$("body").on("ajax:success", '.remote-form', (e, data, status, xhr) ->
    $(this).parent().parent().after(xhr.responseText);
    $.colorbox.resize();
  ).on "ajax:error", '.remote-form', (e, xhr, status, error) ->
    $(this).parent().parent().after("Error");

def create
  @floor = Floor.new(floor_params)
  if @floor.save
    render action: 'edit', layout: false
  else
    render action: 'new', layout: false
  end
end

#popupBox.ajax-target
  %h1 New Floor
  = render 'shared/form_errors', resource: @floor
  #formHolder
    = simple_form_for @floor, html: { multipart: true, class: 'remote-form' }, remote: true do |f|
      = f.input :name, required: true
      = f.input :prefix, required: true
      = f.input :plan, class: 'file_hidden', label: 'Floorplan'

      .clearfix
      = f.button :submit, 'Create Floor'

This works structure works fine for every type of form except ones that have a file input type that have a selected file. If I submit the form with all fields blank, I see the form reloading fine. If I select an image and leave other fields blank (to trigger the validations) I get:

"Error" text because of the ajax:error response. And also see this in the Network tab:

<textarea data-type="text/html" data-status="200" data-statusText="OK">&lt;div class=&#39;ajax-target&#39; id=&#39;popupBox&#39;&gt;
  &lt;h1&gt;New Floor&lt;/h1&gt;
  &lt;div id=&#39;popupErrors&#39;&gt;
    &lt;ul&gt;
      &lt;li&gt;
        &lt;strong&gt;Prefix&lt;/strong&gt;
        has already been taken
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  &lt;div class=&#39;clearfix&#39;&gt;&lt;/div&gt;
  &lt;div id=&#39;formHolder&#39;&gt;
    &lt;form accept-charset=&quot;UTF-8&quot; action=&quot;/floors&quot; class=&quot;simple_form remote-form&quot; data-remote=&quot;true&quot; enctype=&quot;multipart/form-data&quot; id=&quot;new_floor&quot; method=&quot;post&quot; novalidate=&quot;novalidate&quot;&gt;&lt;div style=&quot;margin:0;padding:0;display:inline&quot;&gt;&lt;input name=&quot;utf8&quot; type=&quot;hidden&quot; value=&quot;&amp;#x2713;&quot; /&gt;&lt;/div&gt;    &lt;div class=&quot;input string required floor_name&quot;&gt;&lt;label class=&quot;string required control-label&quot; for=&quot;floor_name&quot;&gt;&lt;abbr title=&quot;required&quot;&gt;*&lt;/abbr&gt; Name&lt;/label&gt;&lt;input class=&quot;string required&quot; id=&quot;floor_name&quot; name=&quot;floor[name]&quot; type=&quot;text&quot; value=&quot;FLR001&quot; /&gt;&lt;/div&gt;
        &lt;div class=&quot;input string required floor_prefix field_with_errors&quot;&gt;&lt;label class=&quot;string required control-label&quot; for=&quot;floor_prefix&quot;&gt;&lt;abbr title=&quot;required&quot;&gt;*&lt;/abbr&gt; Prefix&lt;/label&gt;&lt;input class=&quot;string required&quot; id=&quot;floor_prefix&quot; name=&quot;floor[prefix]&quot; type=&quot;text&quot; value=&quot;FLR001&quot; /&gt;&lt;/div&gt;
        &lt;div class=&#39;clearfix&#39;&gt;&lt;/div&gt;
        &lt;div class=&quot;input file required floor_plan&quot;&gt;&lt;label class=&quot;file required control-label&quot; for=&quot;floor_plan&quot;&gt;&lt;abbr title=&quot;required&quot;&gt;*&lt;/abbr&gt; Floorplan&lt;/label&gt;&lt;input class=&quot;file required&quot; id=&quot;floor_plan&quot; name=&quot;floor[plan]&quot; type=&quot;file&quot; /&gt;&lt;/div&gt;
        &lt;div class=&#39;clearfix&#39;&gt;&lt;/div&gt;
        &lt;input class=&quot;btn&quot; name=&quot;commit&quot; type=&quot;submit&quot; value=&quot;Create Floor&quot; /&gt;
    &lt;/form&gt;
  &lt;/div&gt;
&lt;/div&gt;
</textarea>

Source: (StackOverflow)

rails Remotipart form with Firefox doesn't work

I have this form, which submits well on Safari and Chrome but not in Firefox :

<%= form_for @user, :remote=> true, :html => { :id => "upload_avatar" , :multipart => true} do |f| %>
<%= hidden_field_tag :delete_avatar_pic%>
<%= f.file_field :avatar, :accept => "image/*"%>
<% end %>

Any idea?

Thanks!

Jeremie


Source: (StackOverflow)

Advertisements

Remotipart is changing the action from PUT to GET

I have a story model that serves as a wrapper for many posts. Posts may have photo attachments, and I use remotipart and paperclip to handle the image uploading and processing.

This works perfectly fine when a user POSTS a new post. I want to allow post authors to edit their posts/uploaded images; and this is where the problem occurs.

When a user clicks an edit button I alter the form that I originally used when users create posts so that that same form can be used to edit the post. As part of that I change I modify the <form> tag from:

<form id="new_post_for_story_241" class="new_post" accept_charset="UTF-8" action="/stories/241/posts.json" data-remote="true" enctype="multipart/form-data" method="post" novalidate="novalidate" target="">

to

<form id="new_post_for_story_241" class="new_post" accept_charset="UTF-8" action="/stories/241/posts/287.json" data-remote="true" enctype="multipart/form-data" method="put" novalidate="novalidate" target="">

Again, this works fine to PUT edits if the user doesn't include an image. It breaks, however, if the form contains a new image. For whatever reason, if the user wants to upload a new image as part of the altered form, the form is submitted with a GET action. Triggering this:

Started GET "/stories/241/posts/287.json?post%5Bphoto%5D=champcourse15thgreen.jpg&post%5Bcontents%5D=another+pic%0D%0A&remotipart_submitted=true&X-Requested-With=IFrame&X-Http-Accept=text%2Fjavascript%2C+application%2Fjavascript%2C+application%2Fecmascript%2C+application%2Fx-ecmascript%2C+*%2F*%3B+q%3D0.01" for 127.0.0.1 at 2013-05-22 10:54:50 -0700

ActionController::RoutingError (No route matches [GET] "/stories/241/posts/287.json"):

Anyone know why this is happening, and more importantly, have a fix for it?


Source: (StackOverflow)

js not working after upload picture with ajax

I'm using a remote form to update one model, and I can also upload a new avatar for this model. After the update is completed, there is an update.js.erb file that is called, liked this:

controller

  def update
    @customer = Customer.find(params[:id])
    @customer.update(customer_params)
    respond_to { |format| format.js }
  end

update.js.erb

<% unless @customer.errors.any? %>

  function divSuccess(){
    return "<center><div class='alert alert-success' role='alert'>Client updated.<button type='button' class='close' data-dismiss='alert'><span aria-hidden='true'>&times;</span></div></center>"
  }
<% end %>

it turns out that if I update anything but the avatar on the model, the div on divSuccess appears on my view, but if I update the avatar, this div does not show up, but the model is updated successfuly. I'm using the gem remotipart too

Anyone have seen this? Please, let me know if some info is missing


Source: (StackOverflow)

Async file uploads with Rails 4

I have a form that uses rails jquery-UJS to submit asynchronously. It works fine as long as there is not a file input. When I add a file input, the form stops submitting asynchronously, and instead submits normally (full page reload).

I found out that since browsers do not support ajax files, UJS will fire the ajax:aborted:file event if a populated file input exists in the form. http://robots.thoughtbot.com/a-tour-of-rails-jquery-ujs

The proposed solution is to use remotipart. https://github.com/JangoSteve/remotipart. However this gem hasn't been touched since 2013. I believe I read somewhere that Rails 4 includes this functionality.

What is the Rails 4 convention for async file uploads?


Source: (StackOverflow)

Rails 4 - json.jbuilder with remotipart

My Application details

  1. Rails 4.0 application
  2. Remotipart gem remotipart (1.2.1)
  3. Using json.jbuilder to return a response.
  4. Using paperclip gem for uploading file paperclip (~> 4.1)

I have a form with remote: true and multipart: true. I am redering a json.jbuilder template after submitting the form. I have ajax:successcallback on the form.

When I submit a form without an attachment then it renders json.jbuilder template and ajax:success callback works. But if I submit a form with an attachment then the form gets submitted rendering json.jbuilder file. But the ajax:success callback doesn't work.

I have been struggling with this issue since 2 days.

Thanks in advance


Source: (StackOverflow)

Upload file asynchronously using remotipart on drag and drop

I have my own implementation of text editor and would like to allow users to upload files by dragging and dropping it to the text editor. The editor uses iframe. I am using rails and remotipart to do async upload of image files. I tried using this plugin: http://chrismbarr.github.io/FileDrop/ but I can't figure out how to upload files using remotipart. I tried using AJAX but I am sure it is not the right way and moreover it does not work either:

$('#wysiwygtextfield').contents().find("html").fileDrop(
     {
      onFileRead:function(fileCollection){

           $.each(fileCollection, function(){
    // I should probably be uploading files to the server using remotipart here. 
    // the plugin iterates through the collection of files that are dropped 
          });
                                          },
         removeDataUriScheme: true
     }); 
   }) ;

Please comment if you need more code, the upload action or the html. I am using the following form to do async uploads of files using the remotipart gem and it works fine:

<%= form_for(:image, :remote => true , :url => 'upload',:multipart => true , 
             :html => { :id => 'upload_qimage'}) do |f| %>

 <%= f.file_field :image, :placeholder => 'No file chosen',:onchange => "$(this).parents('form').submit(); before_submit() ; ",class: "image_textbox"  %>

<% end %>

Source: (StackOverflow)

AJAX image upload with Rails, Backbone, Remotipart

I've been using Remotipart successfully to upload images via AJAX for a while now, but we've recently decided to go the Backbone route, and now since my forms are rendered via JS templates, I'm no longer able to use the :remote => true syntax to generate the Iframe transport code. I don't want to have to figure out how to do this manually. Any thoughts on how I can get Remotipart to work when using JS templates?


Source: (StackOverflow)

Error in nested_form when rendering page after submiting form with remotipart

The Application:

In my Rails (v3.2.17) project I have classes:

class User < ActiveRecord::Base
  has_many :photos, dependent: :destroy

  accepts_nested_attributes_for :photos, :allow_destroy => true
  attr_accessible photos_attributes

and:

class Photo < ActiveRecord::Base
  belongs_to :user
  attr_accessible :name, :picture
  has_attached_file :picture, :styles => { :medium => "370x370#", :thumb => "120x120#" }

  validates :name, :presence => true

I use paperclip to handle the picture upload.

In the user form, I use the gem nested_form to dynamically create nested photo forms. My user form view goes like this:

<%= simple_nested_form_for(@user, :remote => true) do |f| %>
  <%= f.error_notification %>

  <div id="photos">
    <%= f.fields_for(:photos) %>
  </div>

  <div class="add_new_photo_container">
    <%= f.link_to_add(:photos, {:id => "add_new_photo", :data => {:target => "#photos"}}) do %>
      Add photo
    <% end %>
  </div>

  <%= f.button(:submit, @user.new_record? ? 'create' : 'update', :id => "submit_form") %>
<% end %>

Inside the form for nested_attribute photo, I have the file_field. As I want to submit user form using Ajax, and files can not be submitted through ajax, I am also using remotipart gem to handle this. My photo_fields is like this:

<%= f.link_to_remove(:class => "remove_photo_form") do %>

<%= f.file_field :picture, accept: 'image/png,image/gif,image/jpeg,image/jpg', :class => 'upload_picture'  %>
<%= f.input(:name) %>

My controller has the create method:

def create
  @user = User.new(params[:user])
  if @user.save
    respond_to do |format|
      format.js {}
    end
  else
    respond_to do |format|
      format.js { render 'reload_form' }
    end
  end
end

And reload_form.js.erb goes like:

$('#user_form').replaceWith("<%= j (render 'users/form') %>");

What does work:

The success case, when I submit User with many photos and specify the name for each photo, does work perfectly.

The error case, when I do submit photos without name (name presence is required) but also without the picture file, does work fine. The form is reload and errors are showed in my html. This is the Rails log:

Started POST "/en/users" for 127.0.0.1 at 2015-06-23 22:31:18 -0300
Processing by UsersController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"RmKyaIap0fJlIECa65oj0PLncYqxyAJ0OzPc7H3eiZg=", "user"=>{"photos_attributes"=>{"0"=>{"_destroy"=>"false", "name"=>""}, "1"=>{"_destroy"=>"false", "name"=>""}}, "starts_at"=>"", "finishes_at"=>""}, "commit"=>"Create", "locale"=>"en"}

What does not work:

The error case, when I do submit photos without name but I upload the picture file, does NOT work.

In this case, remotipart acts to submit the picture in an ajax manner. But there is some sort of error when reloading the f.link_to_add from nested_form. No errors are showed, but the form do not reload either.

And this is the Rails log of Post when it does not work:

Started POST "/en/users" for 127.0.0.1 at 2015-06-23 22:31:53 -0300
Processing by UsersController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"RmKyaIap0fJlIECa65oj0PLncYqxyAJ0OzPc7H3eiZg=", "user"=>{"photos_attributes"=>{"0"=>{"_destroy"=>"false", "name"=>"", "picture"=>#<ActionDispatch::Http::UploadedFile:0x43d5a40 @original_filename="avatar.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"user[photos_attributes][0][picture]\"; filename=\"avatar.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:C:/Users/EVEDOV~1/AppData/Local/Temp/RackMultipart20150623-1552-ka9clf>>}, "1"=>{"_destroy"=>"false", "name"=>""}}, "starts_at"=>"", "finishes_at"=>""}, "commit"=>"Create", "remotipart_submitted"=>"true", "X-Requested-With"=>"IFrame", "X-Http-Accept"=>"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01", "locale"=>"en"}

When I enable exhibition of all kind of errors in Firebug console, that's what I see:

Handler function DebuggerProgressListener.prototype.onStateChange threw an exception: [Exception... "Component returned failure code: 0x80004002 (NS_NOINTERFACE) [nsIWebProgress.DOMWindow]" nsresult: "0x80004002 (NS_NOINTERFACE)" location: "JS frame :: resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/main.js -> resource://gre/modules/devtools/server/actors/webbrowser.js :: DPL_onStateChange :: line 1439" data: no]Line: 1439, column: 0
DevToolsUtils.js (linha 60)
<Sistema>

[Exception... "Component returned failure code: 0x80004002 (NS_NOINTERFACE) [nsIWebProgress.DOMWindow]" nsresult: "0x80004002 (NS_NOINTERFACE)" location: "JS frame :: chrome://browser/content/browser.js :: TabsProgressListener.onStateChange :: line 13564" data: no]
tabbrowser.xml (linha 490)

TypeError: can't access dead object
htmlPanel.js (linha 1082, col 16)
<Sistema>

Does anyone have faced any similar problem and knows how to fix it?

I have also tried to replace nested_form by cocoon gem, but I fall into the same problem.


Source: (StackOverflow)

ajax fileupload through rails remotipart gem

I have been trying to upload images through remotipart and carrierwave. Simply fileupload is working fine, I have also installed remotipart gem which enables file upload through ajax.Now the issue is how to send the file through ajax(I mean the jquery part).

This is how I'm trying to send the file to my controller,but its not working

$("#upload").live("submit",function(e) {

    e.preventDefault();
    var report ={};
    report.file =$("#new_upload").find('#upload_name').val(); 

    $.ajax(this.action, {
        data:  report,
        iframe: true,
        processData: false
    }).complete(function(data) {
        console.log(data);
    });
}); 

Here's my form code:

<%= form_for(@upload,:url => { :action => "save_remotipart" },:html => {:multipart => true },:remote => (params[:action] ==  true )) do |f| %>

  <fieldset>
    <legend class='required'>
      Required fields
    </legend>
      <div class="field">
        <%= f.label :name %><br />
        <%= f.file_field :name %>
      </div>
    </fieldset>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

When the form is submitted No parameters are sent to the server. On abort I'm getting this:

{"object Object"=>nil}

Please help me.


Source: (StackOverflow)

Rails 3 remote link click triggers different request on second click

I have a Rails app that was working well until I upgraded ruby, rubygems, and my gems.

Almost all of my links are remote links. When I make the first request by clicking on one of these links, Fancybox is triggered and opens the new content correctly. When I close the box and click the same link again the request that is generated is completely different. It requests the index and consequently Fancybox is populated with the index response.

Sample link:

<a rel='nofollow' href="/companies/87/edit" data-remote="true">Handmade Design</a>

First request:

Started GET "/companies/89/edit" for 127.0.0.1 at 2013-03-18 15:34:26 -0700
Processing by CompaniesController#edit as JS

Second request:

Started GET "/companies" for 127.0.0.1 at 2013-03-18 15:34:26 -0700
Processing by CompaniesController#index as */*

I'm relying on the jquery-rails gem, fancybox, and the remotipart gem if that helps. Since these were all updated it seems like the error could be in one of these areas, but that fact that the requests are totally different makes me think it's something with Rails formats. Here is what the edit action looks like in the Companies controller:

#/controllers/companies_controller.rb
respond_to :html, :json
respond_to :js,   :only => [:new, :create, :edit, :update, :destroy]

# ...

# GET /companies/1/edit
def edit
  respond_with @company
end

I use a before filter to grab the company.

Any help or clues would be much appreciated.

UPDATE

The second request appears to always be a request for the current page.

UPDATE

I've isolated this to a JS issue. It appears to not be an issue with Rails or remote links.


Source: (StackOverflow)

Ajax file upload with Remotipart works on development, 406 on heroku

I have a series of remote forms on a page, each of which should be able to upload a file when the object is updated or created. I've checked and tested thoroughly in development, and as long as I'm using Remotipart this seems to work just fine.

However, this morning I pushed my changes up to my staging server on Heroku, and when I try to submit one of these forms with a file upload, I get a 406 Not Acceptable response from the server. So here my page does not get updated because I don't get my expected js template response from the server. However, if I reload the page, the file I tried to upload shows up just fine.

The forms are created using simple_form (with remote: true) and I'm using Carrierwave with Fog to upload the files to S3 (also tested in development, so I don't think it's that).

The network inspector shows the same kind of data as far as I can tell. I see no significant differences in the request payload.

I don't know what I'm doing wrong (if anything). Has anyone else experienced this or perhaps have an idea what's wrong?

Update

So I've figured at least one thing out. My controller was only handling js format requests. I handled html formatted requests by redirecting to another path, and the html of that page is now sent back as the ajax response. What I can't seem to figure out is why, when the content types and everything seem to be the same on both development and staging, do the responses get sent/rendered in the wrong format.


Source: (StackOverflow)

Rails Jquery upload file using remotipart gem NoMethodError: undefined method `name'

I am using gem remotipart for uploading file. Here is my view:

<%= form_for @file_upload, :id => "form_feedback_attachment", :url => { :controller => "widgets", :action => "feedback_attachment_upload" }, :html => {:multipart => true} do |f| %>
   <td class="rightcol"><%= f.file_field :feedback_attachment, :id => "feedback_attachment_file" %>
   <%= f.submit "Upload" %></td>
<% end %>

My controller:

@file_upload = FileUpload.new
    @file_upload.feedback_attachment = params[:file_upload][:feedback_attachment]
     respond_to do |format|
      if @file_upload.save
        format.js
      end
    end

But I get this error : NoMethodError: undefined method `name' for nil:NilClass. I have no idea from where is the method name and from which Class. Any help would be really appreciated. Thanks


Source: (StackOverflow)

Do I need to reload the comment object or the partial that contains the comment in case of using Ajax in Rails 3?

I have been trying to figure out adding comments without reloading the page using Ajax, after reading few different tutorials this is what I came up to so far, and it's not working:

inside user_comments/_comments.html.erb

    <div id="comment_form">
  <%= simple_form_for [@commentable, @comment], :html => { :multipart => true }, :remote => true do |f| %>
    <div class="picture"><%= image_tag current_user.avatar.url(:thumb) %></div>
    <%= f.input :content, label: false, :placeholder => "Add Comment", :input_html => { :rows => 4 } %>
    <%= f.submit "Add Comment" %>
  <% end %>
   </div>

Inside the controller:

def create
@users = User.all
@comment = @commentable.user_comments.new(params[:user_comment])
@comment.user_id = current_user[:id]
#@commentable.user_comments.create(:user_id => current_user[:id])
if @comment.save

  flash[:notice] = "Successfully created comment."
  respond_to do |format|
    format.html { redirect_to @commentable }
    format.js
    #format.js #{ render 'create.js.erb' }
    end
else
  render :new
end
 end

and inside the create.js.erb

// Display a Javascript alert
<% if remotipart_submitted? %>
    $("#comments_list").append("<%= escape_javascript(render(:partial => 'user_comments/comments')) %>");
<% end %>

I'm using a Gem called: remotipart

I don't know what I'm missing in the process. in the console I get:

POST http://localhost:3000/assignments/2/user_comments

200 OK
        134ms

which means the post goes through, but the comment doesnt get added back to the partial.


Source: (StackOverflow)

AJAX file upload using Remotipart and Carrierwave

I have a model that has an icon associated to it. This icon upload is managed by Carrierwave.

My issue arises when I try to send the file via ajax from my form.

My Model is as follows:

class Category < ActiveRecord::Base

   attr_accessible :name,
                   :icon
   mount_uploader :icon, TemplateCategoryIconUploader

 end

Controller action:

def update
    @category = Category.find(params[:id])
    @category.update_attributes(params[:category])

    if @category.save
      flash[:notice] = "Category Updated!"
      render_ajax_content_replace :element => :show_category, :partial => 'show'
    else
      render_ajax_content_replace :element => :show_category, :partial => 'show'
    end
  end

And finally my form:

<%= form_for @category, :html => {:multipart => true}, :remote => true do |f| %>

        <%= error_messages_for f.object %>

       <%= f.file_field :icon %>
<% end %>

Removing the ajax side of thing allows the submit to work. However I require it to be done with AJAX.

The error I get is a missing template error. However all my partials exist and work. For some reason the render_ajax_content_replace breaks. Its simply supposed to replace an element with a partial. This works perfectly everywhere else. Adding AJAX files breaks it.


Source: (StackOverflow)