使用Rails提交Ajax表单

In my Rails app, I want to update a model when the user uploads an image. The image gets rendered on the page immediately after the image is selected but the image should get uploaded in the background as an AJAX call. In other words, the form should be submitted without the user having to click a submit button - it should automatically submit the form once the file is selected.

In my current implementation, the newly uploaded image appears on the page, but it triggers an HTML update that causes the page to refresh even though remote is set to true on the form. How do I ensure that the form is submitted as an AJAX request?

(I followed the example on this page: Submit form in rails 3 in an ajax way (with jQuery))

 <%= form_for [@collection], :html => {:id => "collection_avatar_form" }, :remote => true do |f| %>
      <div id="uploadImageWrapper" title="Edit Avatar">
         <%= image_tag(@collection.image_url(:thumb), :class=>"img-rounded") %>
         <div id="editAvatarIcon"><icon class="fa fa-pencil"></icon></div>
         <%= f.file_field :image %>
     </div>
<% end %>

Which creates this HTML:

<form accept-charset="UTF-8" action="/collections/introduction-to-product-design--3" class="edit_collection" data-remote="true" enctype="multipart/form-data" id="collection_avatar_form" method="post">

Javascript:

  $('#collection_image').change(function(){
    var F = this.files;

    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(F[0]);  
    reader.onload = function(_file){
        image.src    = _file.target.result;        
        image.onload = function() {
            $('#collectionAvatar').find('img').attr('src', this.src);
        };
    }
    $('#collection_avatar_form').trigger('submit.rails');
  });

You should use

$.post('yourURL', this.form.serialize())

instead of

this.form.submit();

This is what ended up working for me (where #collection_image is the id of the file_field and #collection_image_form is the form)

$('#collection_image').change(function(){
    var F = this.files;

    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(F[0]);  
    reader.onload = function(_file){
        image.src    = _file.target.result;              
        image.onload = function() {
            $('#collectionAvatar').find('img').attr('src', this.src);
        };
    }

    $.ajax({
          type: "POST",
          url: $('#collection_avatar_form').attr('action'), 
          data: new FormData($('#collection_avatar_form')[0]),
          processData: false,
          contentType: false,          
          dataType: "JSON" 
      }).success(function(json){
          console.log("success", json);
    });

  });