views:

84

answers:

2

This is probably a really dumb question with a simple answer but...

I am working on a project where I need to use AJAX to send/receive information. I am using Ruby on Rails (which I am pretty new to), but rather than using the helper methods or the built in functionality in the 'defaults' Javascript file, I need to do this manually in my own Javascript.

I believe that ultimately I will want to send a request with a JSON object, then have the controller return another JSON object containing the requested information.

The problem is that I cannot seem to find the syntax for sending something to a specific controller method, with parameters, directly from Javascript - everything I Google ends up being tutorials for using the Rails AJAX helper methods.

+1  A: 

if using jQuery is an option for you, jQuery.ajax will solve your problem.

[and for those who likes to say jQuery is not solution for everything, i know that. i'm just giving him an option].

j.
Never used jQuery, but that is looking promising. Do you know if adding in jQuery will break the existing Rails AJAX support? (or anything else Javascript related for that matter)
Zachary
I don't think it will break anything. I use jQuery at work and this is very helpful. take a look at http://api.jquery.com/jQuery.ajax/
j.
jQuery can break things by overriding the "$" selector. You can fix this by calling noConflict (http://api.jquery.com/jQuery.noConflict/) or switiching JavaScript provider via my answer.
Mike Trpcic
+3  A: 

Depending on the version of Rails you're using, you can do the following:

  1. Install the jrails plugin. This will replace all the Prototype javascript in your application with jQuery. This means you now have access to all the jQuery libraries, but it won't break your existing rails helper stuff (remote_form_for, etc).

  2. Now you can use the jQuery AJAX to make any AJAX requests you want to make. A simple example would be something like below:

    //Let's get a specific post by id
    $.ajax({
        type: "GET",
        url: "/posts/123",
        success: function(data){
            //put the data in the DOM
        }
    });
    

Then just add the appropriate respond_to in your controller:

PostsController < ApplicationController
  def show
    @post = Post.find(params[:id)
    respond_to do |w|
      w.json { render :json => @post.to_json }
    end
  end
end
Mike Trpcic
+1: Thank you for the great example.
Zachary