2

In my rails app I have a javascript callback after the a post is created that polls a processing endpoint to check if an image has finished processing and then updates the view like this:

create.js.erb create callback

// start polling for processed image
function imageProcessed() {
  $.ajax({ url: "/posts/" + <%= @post.id %> + "/processing"})
    .done(function(data) {
      if (data.processing) {
        setTimeout(imageProcessed(), 2000);
      } else {
        // append image url when processed
        $("#js-capture-container").html('<img src="' + data.image_url + '" alt="image">');
      }
    });
}

imageProcessed();

posts_controller.rb endpoint

def processing
  data = { processing: @post.image_processing }
  if !@post.image_processing?
    data[:image_url] = @post.image_url(:pair)
  end
  render json: data
end

This works fine, but I would like to take the data returned in the ajax and render the already existing _post.html.erb partial with this data.

Something like return an updated instance of @post and then render that object into the partial.

"<%= escape_javascript(render @post) %>" in create.js.erb

Any ideas would greatly help, thanks!

Chris Williams
  • 412
  • 3
  • 16
  • Usually for this you would initially have rendered out a partial which uses the @post object. Then, you can update the post with your data from params, and then do `render :partial => "posts/my_partial", :locals => {:post => @post}` or something like that. – Max Williams Sep 02 '15 at 16:26

1 Answers1

1

I was able to get it work by rendering the partial as a string of HTML inside of the json object, similar to what's being done in this question: rails 3 - How to render a PARTIAL as a Json response

I changed the if statement in post_controller.rb to:

if !@post.image_processing?
  data[:partial] = render_to_string(@post)
end

and then in create.js.erb changed the callback to:

$("#js-capture-container").html(data.partial);

very nice, very clean.

Community
  • 1
  • 1
Chris Williams
  • 412
  • 3
  • 16