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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.