0

bit new to Ajax and rails.

I have a link on an image that when clicked should replace the image.

Here's my link in the view:

<div id="flag_<%= message.id %>">
  <%= link_to image_tag("white_star.png"), flag_message_path(message), remote: true %>
</div>

this calls flag method on messages controller. For format.js i have flag.js:

{$('#flag_<%[email protected]%>').html('<% if @message.flag == false %><a href="/messages/96/flag" data-remote="true"><img alt="White_star" src="/assets/white_star.png" title="flag"></a>
    <% else %>
    <a href="/messages/96/flag" data-remote="true"><img alt="Red_star" src="/assets/red_star.png" title="flag"></a>
    <% end %>');
}

this returns to the browser:

{
$('#flag_94').html('<a href="/messages/96/flag" data-remote="true"><img alt="White_star" src="/assets/white_star.png" title="flag"></a>
');
}

which seems ok to me, yet nothing happens.... Any thoughts?? thanks

1
  • was wondering if it is anything to do with the quotation marks, but can't get it right Commented Dec 16, 2012 at 14:30

1 Answer 1

1

Everything seems ok, but I would drop the surrounding accolades in your format.js.erb. Those are not needed.

If there is an error in your javascript, you should see it in the javascript console.

It is generally good practice to extract code like this into a partial.

So you would have a replace_image.html.erb :

<% if @message.flag == false %>
  <a href="/messages/96/flag" data-remote="true"><img alt="White_star" src="/assets/white_star.png" title="flag"></a>
<% else %>
  <a href="/messages/96/flag" data-remote="true"><img alt="Red_star" src="/assets/red_star.png" title="flag"></a>
<% end %>

and in your format.js.erb you would just do

$('#flag_<%[email protected]%>').html("<%= escape_javascript(render :partial => 'replace_image') %>");

Hope this helps.

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

1 Comment

Thanks!! escaping seems to have done the trick, also had some \n floating in there.

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.