views:

375

answers:

2

If I have user interactions in my Javascript layer, can I have Javascript actions trigger Rails controller actions and pass data from Javascript to those Rails methods?

A: 

I believe you can make AJAX requests back to your controllers. Rails by default includes prototype so you can use its AJAX functionality ( http://www.prototypejs.org/api/ajax/request )

alex
+4  A: 

Yes. You make asynchronous calls back to your Rails application using XMLHttpRequest, typically through Prototype or some other Javascript library. You pass data back to the server using query parameters, much like any other request, and your application returns HTML fragments or Javascript code that is used by the browser to update the relevant parts of the page.

The PrototypeHelper class is useful for generating the right stuff in the server. Ajax.Request is what you'll use on the client.

Steve Madsen
Very helpful. Thanks. So basically Ajax.Request is sending the XMLHttpRequest from the client with my Javascript data as query parameters and then in my Controller I use PrototypeHelper to translate the received query parameters into data that my application can understand?
carson welsh
You've almost got it. The incoming data looks like a regular request, with data in params[]. You can check if it's an XMLHttpRequest with request.xhr?. PrototypeHelper is a view helper; it gives you convenience methods to produce a partial response so you don't have to resend the entire page.
Steve Madsen
Thanks. That'll get me started.
carson welsh