Rails AJAX_OPTIONS :with
Posted by Matt White, Wed Feb 21 15:05:00 UTC 2007
The Problem
I’m writing an admin backend for a client, and I wanted to trigger an AJAX call based on the value of a SELECT field. The problem this presents compared to the normal Rails AJAX usage is that the value you want to send via AJAX isn’t specified at the time the page is rendered, and I didn’t want to serialize the entire form to get the correct value of one field.
The obvious candidate for a link to fire an AJAX call is link_to_remote, but it’s not entirely obvious how you can specify a request parameter that will be evaluated at the time of the click. Most of the time you set the parameters you wish to send back to the server in the URL, but that won’t work in this case because I don’t want to use a static URL.
.h2 The solution: ”:with” So, there’s a handy option to most of the PrototypeHelper functions that’s a bit poorly documented (in my opinion, anyway). :with allows you to specify the parameters part of the Ajax.Request call. This will be evaluated on the fly when the onclick is fired, and is submitted via POST. (Unless you are setting the postBody parameter as well.) The best part is that Prototype will serialize standard JavaScript object notation (read: JSON) into a URL-encoded POST body. Not too clear? Try this:
link_to_remote("Set Position",
:url => {:action => "load_map", :id => @listing},
:with => "{map_id:$F('listing_map_id')}")
This will yield the following HTML/JavaScript:
<a href="#" onclick="new Ajax.Request('/property/show_map/1',
{asynchronous:true, evalScripts:true,
parameters:{map_id:$F('listing_map_id')}});
return false;">Set Position</a>
Which will, when clicked, generate an AJAX call with the following POST body:
map_id=1
(assuming the value of my dropdown is 1.) Also, note that $F is a Prototype shortcut that allows you to grab the value of a form field based on the ID you pass in. An extremely handy function…
So, this is a really great way to add an arbitrary number of parameters to an AJAX call using any Javascript variable, which could be the position of an element, value of a form field, the list goes on!