Rails + JQuery: Can not update span content with Ajax query
I have some trouble using an Ajax query in a Rails + JQuery ecosystem. What I want to do is to update the content of a span with the answer to 开发者_开发知识库an AJAX request when I click on a link.
Here is the interesting part of my view:
<div class="field">
<%= f.label "Avatar (laissez vide pour utiliser votre gravatar)" %><br />
<span id="avatar">
<%= gravatar_for @user %>
</span><br />
<%= link_to "Editer votre gravatar", "http://www.gravatar.com/emails", :target => :_blank %><br />
<%= f.file_field :avatar %>
<%= link_to "Supprimer avatar", "/users/new/delete_avatar?id=#{@user.login}", :remote => true, :confirm => "Etes-vous sur?" %>
My goal is to update the span with the ID "avatar" when when click on the last link. Here is the code that receive the request:
def delete_avatar
user = User.find_by_login(params[:id])
user.avatar.destroy
respond_to do |format|
format.html { redirect_to edit_user_path @user }
format.js
end
end
And here is the delete_avatar.rb.js file, called by the respond_to:
$("#avatar").html("<%= gravatar_for @user %>");
Now, when I click on the link and use the query analysis tool of Firebug, what I get is a GET request, with an status code 304 or 200 depending on if the content is the same as before or not, with the following content:
$("#avatar").html("<img alt="foobar" class="gravatar" src="http://gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?size=150&default=http%3A%2F%2Fskullslab.elhu.me%2Fimages%2Fskl_avatar.png" />");
This seems to be what I'm expecting, but I don't know why, the content of the page isn't modified.
I've been stuck on this for a few hours now, and I'm quite sure the answer is really straightforward... but I'll be grateful for any kind of help, thanks!
PS: JQuery is correctly loaded into my app, since I'm able to update the content of a span when clicking a link when I'm not trying to use AJAX.
You will need to javascript escape your garatar_for in rails code, like this:
$("#avatar").html("<%= escape_javascript gravatar_for @user %>");
The problem is that you are having qoutes (") in your string, and that makes the javascript illegal. (unless you use ' for the jquery html method instead of ", but thats just a bad workaround)
Also, it may be a good idea to watch this little exelent screencast from RailsCasts on rails and jQuery. He mentions this in that episode: http://railscasts.com/episodes/136-jquery
Hopes this helps you out
精彩评论