Search code examples
jqueryruby-on-rails-4jquery-file-upload

how to render javascript in update action with jQuery-File-Upload and Rails 4


I'm using jQuery-File-Upload which allows for AJAX-y file uploads. I'm using it for users to change their avatar image without having the entire page reload. This is covered in RailsCast 381 but I cannot get it to work. The user can do this in the edit/update actions by choosing a new file to upload. This happens at authors/:id/edit

My javascript:

$(document).ready(function(){
  $('#image-form').fileupload();
});

I watch the Network tab inside Chrome and when I "Choose File" a POST action is fired which runs the "authors#update" action. Inside which I have this code:

@author.update(author_params)

The update code updates the image file in my database. Inside update.js.erb I tried to put the following code:

$('#image').html("<%= @author.image_url %>");

But it never executes. I know the code inside the update action executes because when I refresh the page at authors/:id/edit the new image appears. But I want it to happen on the fly. But I just can't figure out why update.js.erb is not being called.


Solution

  • Figured it out. Rails was wrapping the javascript response in a layout. The solution was the following inside my update action:

    respond_to do |format|
      format.js { render layout: false }
    end