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 [email protected]_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!

1
  • 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. Commented Sep 2, 2015 at 16:26

1 Answer 1

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 [email protected]_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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.