Rails newbe here. I've got links that do ajax query to server:
<%= link_to g.name, g, :class => 'link link-to-gallery', :remote => true %>
JS view that loads data from partial:
$('#content').html('<%= escape_javascript render("layouts/galleries/show") %>');
And controller that operates with models and renders html and js:
class GalleriesController < ApplicationController def show @galleries = Gallery.all @gallery_to_show = Gallery.find(params[:id]) respond_to do |format| format.html format.js end end end
Ajax works fine, but I try to put callback after ajax completed:
jQuery(function() { $(".link-to-gallery").bind("ajax:complete", function() { alert(1) }); });
and alert never shows. What am I doing wrong? Rails version is 3.2.11, Ruby version is 1.9.3p194
Update: When I'm using this code
jQuery(function() { $(".link-to-gallery") .on("ajax:before", function () { alert("before") }) .on("ajax:complete", function() { alert("complete") }); });
"before" alert fires but only once. If I press again I gain nothing. But ajax still works.
I think the problem is with your controller method that is not responding the async call with a success status message, 200.
Try this
def show
@galleries = Gallery.all
@gallery_to_show = Gallery.find(params[:id])
respond_to do |format|
format.html { :status => 200 }
format.js { :status => 200 }
end
end
If that doesn't work, try this.
def show
@galleries = Gallery.all
@gallery_to_show = Gallery.find(params[:id])
respond_to do |format|
format.html { :status => :ok }
format.js { :status => :ok }
end
end
It seems that I'm lame but smart enough to fix this. I had these links:
<%= link_to g.name, g, :class => 'link link-to-gallery', :remote => true %>
in the partial which gets re-rendered after ajax. So the callback functions that were attached to these links were flushed away after ajax. So I put link out of this partial and it works now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.