thoughtpunch
thoughtpunch

Reputation: 1937

Passing Javascript to Rails controller on POST + clickable Google Maps markers

In my Rails application I am using the Google Maps AutoComplete API to allow users to search for locations like so:

Places autocomplete API + Javascript Map API

The javascript code (Gist here...) returns a JSON hash and places a new marker with the choice from the drop down box. I have a listener for the marker that does nothing right now, which leads to my question.

  1. How do I make the 'click' event for the marker pass the the result hash (in this case 'place') to a rails controller?
  2. More generally, how does one pass JavaScript data to a Rails controller at all?

I've looked over other answers and can't find a solution. Any help would be greatly appreciated.

Thanks!

~Dan B,

@thoughtpunch

Upvotes: 2

Views: 1128

Answers (2)

Joe Steele
Joe Steele

Reputation: 141

You'd use jQuery to do a 'GET' and pass the parameters you need. So based on your gist, you have an address string you built. In your controller you would send back the response which would be handled in the callback. You could send back the JSON and do something with that client-side or just send back the html to insert.

google.maps.event.addListener(marker, 'click', function() {
  // maybe a loader here?
  // $('#reviews').html('loading reviews for ' + address + '...');
  $.get('/reviews', {address: address}, function(data) {
    $('#reviews').html(data);
  });
});

And that data could be anything that you want as a param. You could send the whole place if you wanted. '{place: place}'

Upvotes: 2

user324312
user324312

Reputation:

JQuery can serialize data in all of it's ajax related methods; you can use this to post raw json to the server:

$.post("/foo", {place: {foo: "bar"}})

On your controller:

def action
  render :text => "Got: #{params[:place]}" # output: 'Got : {"foo":"bar"}'
end

You'll probably want to either only post the fields from your locations you care about or use JSON.parse to unserialize your json strings for manipulation server-side.

Upvotes: 3

Related Questions