NullVoxPopuli
NullVoxPopuli

Reputation: 65173

Ruby on Rails3: How do I invoke javascript before an ajax event is fired with remote => true?

        <%= link_to( {:controller => 'board', 
                          :action => 'take_turn', 
                          :id => @board.id,
                          :x => col, 
                          :y => row} , :remote => true, :onClick => "return links_disabled;") do %>
          <div class="ttt_square"> 
            &nbsp;
          </div>
        <% end %>

in rails2, there were :before, and :complete params, but I have not found any documentation for this in rails3

Upvotes: 0

Views: 620

Answers (4)

Brian Deterling
Brian Deterling

Reputation: 13734

My version (jquery-rails 0.2.6) supports ajax:before, loading, success, complete, failure, and after. The parameters to the success/failure functions are not the same which has tripped me up in the past. But the following works for me:

$('a').bind('ajax:loading', function() {
  alert('here');
});

If your link element was created after the initial page load, you might need to bind using 'live':

$('a').live('ajax:loading', function() { alert('...'); });

I would also double-check that your onclick handler is not interfering.

Upvotes: 0

doctororange
doctororange

Reputation: 11810

As far as I understand, in Rails 3 you bind the callback events to the element on the client side, and they are fired by rails.js at the appropriate times.

$('#myform').bind('ajax:success', function(){
    alert('I succeeded');
})

Upvotes: 1

Grav
Grav

Reputation: 1724

As I understand it, this is one of the consequences of Rails 3 using UJS (unobstrusive javascript). Rails 3 enables you to keep the javascript away from e.g. a link-tag. Instead of the link-tag specifying what should be done via javascript, you make the javascript observe the link-tag.

You achieve this by binding a function to a certain event of an object, eg. binding the ajax:before event of the link-tag to a function.

In this blog post the author explains how to do it, in his case with JQuery.

Upvotes: 1

apneadiving
apneadiving

Reputation: 115541

If I remember well, there is no more support in Rails3.

You could use native jQuery function:

ajaxStart()

http://api.jquery.com/ajaxStart/

See details here: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

Upvotes: 0

Related Questions