views:

54

answers:

1

hi,

I have a page which shows a Google map. I'd like to use Javascript to fetch several points from my database and place them as markers on the map. So the flow is:

  1. Javascript calls a Rails action with parameters.
  2. Rails queries the database.
  3. Rails returns the response.
  4. Javascript updates the page (Rails can't do this since it must be aware of the JS map object).

What is the current best practice for implementing such a scenario? I know I can use a Prototype Ajax.Request to call the Rails action but how should I call the Javascript function which updates the page when the Rails action returns its results? Should I update some hidden HTML and have an event listener listen on it? Or is there a better way?

+2  A: 

You have a couple options.

1) Your ajax request can be of type 'script' which will allow you to write an action_name.js file that your rails app renders. This has access to all of your page items (it's not likely to have access to your map object however unless that's public)

2) My preferences is to have your javascript query for json data (type 'json') which then allows you to use that data as you please in your JS. I don't use prototype but the general flow would be.

  • initialize your map
  • query for some json data using ajax (ie. locations with lat/long)
  • rails reponds_to do |f| f.json { render :json => some_hash} end
  • in your ajax callback (back in javascript), iterate over json data and add points to your map appropriately. (or do whatever you like)
brad