Generating data for AJAX req in Rails on the fly

UPDATE
It is possible – read in next post.

Well… I’m starting with AJAX, and my first impressions are very positive. I was skeptical to JS but more I try more I like it. Maybe I don’t like troubles with debugging (like – does know anyone if Venkmann can set breakpoint in JS code embedded in HTML, not in standalone files?).

Go back to details. In Rails there are helpers like link_to_remote, remote_functions, etc to make AJAX fun and easy. But just at start I run across issue. I’m experimenting with some Google Maps mashup and I wanted to call XHR request with data generated in JS on my page. And looks like I can not find way to mix Rails helper with JavaScript generated data. Let’s take example: I want to pass bounds of current map via XHR to find all points covered by current map. I prepared via call to map.getBounds data in string called dataForSearch. So ideally I could use helper remote_function (:update => 'results', :url => {:action => search_points}, :parameters => 'dataForSearch'). Unfortunately, there is no :parameters option.

So I did check what Rails generates from helper remote_function and read doc to Ajax.Updater (since Ruby on Rails uses script.aculo.us) and there is parameters option. So instead of using Rails helper I needed to hardcoded JS call. Final code looks similar to this:

bnd = map.getBounds();
dataForSearch = 'swlat='+
bnd.getSouthWest().lat().toString()+
';swlng='+ bnd.getSouthWest().lng().toString()+
';nelat='+ bnd.getNorthEast().lat().toString()+
';nelng='+ bnd.getNorthEast().lng().toString(); 

new Ajax.Updater('results', '/route/search_points', 
{parameters:dataForReq, asynchronous:true, evalScripts:true}); 

Well it would be much nicer if it can be done just with Rails helper – or someone knows how to accomplish?

UPDATE
It is possible – read in next post.

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.