0
votes

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.

2
Did you try using on, the preferred mechanism in jQuery 1.7+?Dave Newton
Is your callback code getting overridden by the call in the js view ? Also @Dave Newton made a good point. You should be using on instead of bind of jquery to handle events.bullfrog
Tried this. Same thing as with "bind". But I have some new info.franza

2 Answers

0
votes

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
0
votes

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.