@John
Using jQuery and AJAX in your Rails app is a little more involved than you might think. There is a recent blog article that shows you how to setup jQuery and AJAX when using Rails. Basically, you need to do the following:
Tell Rails how to Handle AJAX calls
applications.js
jQuery(document).ready(function($) {
//Tell Rails that we’re sending a JavaScript request
$.ajaxSetup({
'beforeSend': function (xhr){
xhr.setRequestHeader("Accept", "text/javascript")}
});
//General helper for forms submitted via ajax
$("form.remote_for").submit(function (){
$('input[type=submit]').attr('disabled', 'disabled');
$.post($(this).attr('action'), $(this).serialize(), null, "script");
return false;
});
});
Then when you create your form, add the remote_for class to the form definition:
<% form_for([@post, @comment], :html => { :class => "remote_for" }) do |f| %>
. . .
<% end %>
This will automatically send any forms with the remote_for class as an AJAX request.
Setup your controller action to process AJAX requests
def action
@model = Model.find(params[:model_id])
respond_to do |format|
format.js #auto-maps to action.js.erb
end
end
Place your jQuery code in action.js.erb
app\views\controller\actions.js.erb
This is where the magic happens. It's here that you can combine your Rails objects with your JavaScript and jQuery client-side code. When complete, Rails will send your jQuery back to the client's browser as an AJAX response. Awesome!
$("#request_artist").autocomplete({
source: function(req, add){
<%= @artist.name %>', req, function(data) {
var suggestions = data.suggestions;
add(suggestions);
});
},
});
The article does a better job of walking through a specific scenario. But, it'll allow you to move from inline jQuery to using better separation of concerns. This is also the same technique for using jQuery and AJAX in your rails app instead of the RJS tutorials you might have seen.
Well, it looks like you're moving in the right direction. Good Luck!