1

I have a variable inside application.html.erb's <script>:

...
<script>
  ...
  pos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };
  ...
</script>

Is there a way to pass it down to one of my controllers (posts_controller.rb)'s method (some_method)?

I need to get both latitude and longitude that is generated inside the script into posts_controller. How can I do this?

EDIT: (I didn't mention it, but some_method does not use get 'some_method', but post)

#routes
post 'some_method' => 'posts#scrape', as: :some_method
Iggy
  • 5,129
  • 12
  • 53
  • 87

1 Answers1

1

GET request

You could use

window.open("/posts/some_method?longitude="+pos['lng']+"&latitude="+pos['lat'],"_self")

inside your <script>.

POST request

With jquery, you could use :

$.post("/posts/some_method?longitude="+pos['lng']+"&latitude="+pos['lat'])

For vanilla javascript, see this answer.

In some_method, longitude and latitude will be available in params[:longitude] and params[:latitude].

You can set instance variables (e.g. @lat and @lon) inside some_method, and those variables will be available in the corresponding view.

Community
  • 1
  • 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
  • Hi Eric! Thanks for the response. I did not elaborate (which is entirely my fault), but some_method is not a GET request, but a POST request. Can you suggest another method to pass down variable to a non-GET method? I edited my post to add the method. – Iggy Dec 30 '16 at 15:35
  • Thanks! Sorry that I keep asking, but now that I used jquery to post `longitude` and `latitude` attributes for `Post`, how can I capture it on `some_method` (and display it on views?) Much appreciate the help! – Iggy Dec 30 '16 at 18:58