Rails 3.1 — Fixing the 'ajax:loading' event

Stamped: 2011-05-19 00:00:00 -0400 | Show comments

Having difficulty getting the ajax:loading event to trigger? All you have to do is use ajax:beforeSend instead! An example:

Our example coffeescript:

$ ->
    toggleLoading = -> $("#loading").toggle()
    $("#loading").toggle()
    $("form[data-remote]")
        .bind('ajax:beforeSend', toggleLoading)
        .bind('ajax:complete', toggleLoading)
        .bind('ajax:success', (event, data, status, xhr) ->
            $("#list").html($.parseJSON(data))
        )
        .bind('ajax:error', (xhr, status, error) ->
        )

Our form:

<%= form_for @profile, :id => "hours_form", :url => {:action => :show }, :remote => true do |f| %>
    
    <%= field_set_tag do %>
        <%= f.label :profile_name %>
        <%= f.text_field :profile_name %>
    <% end %>
    
    <%= submit_tag 'Submit', :id => "submit" %>
    
<%end%>
<div id="loading">
Loading...
</div>

And finally, the controller:

class ProfilesController < ApplicationController

  def index
    @profile = Profile.new
  end
  
  def show
    @profile = Profile.find(p.id, :include => :games)
    
    respond_to do |format|
      format.html
      format.js { render :json => @profile }
    end
  end
end
tags: rails, ajax, jquery
recent entries
Rails — A faster way for next and previous links on a post, article, or any model
The awkward things Siri says
Node.js — Getting oAuth Up and Running Using Express.js and Mongoose
Node.js — Getting oAuth Up and Running Using Express.js, Railway.js and Mongoose
Migrating from Rails 3.1 RC4 to RC5 using Heroku's Cedar Stack (also compass, unicorn, and sendgrid)
Random Freeze Fix for GTX 460 in 10.6 (osx86)
Wasted on Steam - an analytic tool for the Steam platform
Rails 3.1 — SQL logging to STDOUT during testing (with rspec, test::unit, or cucumber)
Rails 3.1 — Using ERB/HAML/etc within a Coffeescript JS file
Rails 3.1 — 'load_missing_contant': Expected ... to define ... (LoadError)
View the entire archive of articles