Rails Basics - Using rails routes in jQuery ajax callbacks

These “Rails Basics” blog posts are simple how-to’s for Rails 3. These are aimed at beginners to Rails, but prior programming knowledge will be helpful. This post will assist you in using rails routes while doing jQuery ajax callbacks.

Doing an ajax callback with rails would normally look something like this:

$.ajax({
  url: '/posts/3/comments/1/edit',
  data: { },
  async: true,
  dataType: 'script'
});

The URL string above would probably be a concatenated string you build by specifying the URL structure, and inserting in the relevant id's. The problem with this is that you are not utilizing your routes, and any change to your routes could break your code.

A better way to do this is by setting your rails route to a custom attribute on the html object that initiates your ajax call (or it could be stored in a hidden input on the page).

For example, if I have a hyperlink that is the trigger for this ajax callback, I could specify it in my view as:

<%= link_to 'Edit', '#', :id => "edit_comment_link", :ajax_path => edit_post_comment_path(@post, @comment) %>

You will note I have added a custom attribute to my hyperlink that is called ajax_path.

Then in my jquery, I can do the following:

$('#edit_comment_link').live("click", function() {
  $.ajax({
    url: $(this).attr('ajax_path'),  
    data: { },
    async: true,
    dataType: 'script'
  });
  return false;
});

Now if my routes change, my ajax callback will still work.

By Joel Friedlaender