Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails JS Response, render both status and template?

In my current rails app I'm using an ajax uploader library that requires you respond with json {success:true} to indicate a file was uploaded successfully.

In my app the files are images, and after upload I would like to add this to the page. Normally I would do something like:

respond_to do |format|
  format.html { redirect_to @resource, :notice => 'Created.' }
  format.js
end

In the above example my JS response would render the appropriate template, such as create.js.erb which might say something like...

$('#resources').append('<%= escape_javascript( render '@resource' ) %>');

This is how I have done things like Ajax comments etc. in the past. Now, to get the uploader working my respond_to block currently does this:

format.js { render :json => { :success => true } }

This makes the uploader work but seems to preclude me adding rendered partials to the page like I normally would with an Ajax response.

My question is, is there any way to accomplish both? If not, how would you populate the page with rendered objects after they have been successfully created?

like image 931
Andrew Avatar asked Oct 09 '22 11:10

Andrew


1 Answers

You can't do both directly from the controller or using view templates. It looks like ajax uploader is expecting a response that can be parsed as JSON, so adding any other response using a template (which would mean not doing format.js { render :json => { :success => true }}) will not send back JSON as the response body.

Looking at the source for the plugin, you can see that you can define a method to run onComplete which will give you the JSON response.

This is untested, but should get you close. So you if extend your JSON response like

format.js do
  partial = render_to_string @resource
  render :json => { :success => true, :partial => partial }
end

Then in your javascript on the page when you setup your ajax uploader, add the callback

var uploader = new qq.FileUploader({
  element: document.getElementById('file-uploader'),
  action: '/upload',
  onComplete: function(id, fileName, responseJSON) {
    $('#resources').append(responseJSON.partial);
  }
}); 
like image 131
danivovich Avatar answered Oct 13 '22 12:10

danivovich