3

I am trying to set a ruby instance variable's value to the latitude and longitude values. How would you set the value of an instance variable inside a javascript function?

Something like this?

<script>
    if (geoPosition.init()){  geoPosition.getCurrentPosition(geoSuccess, geoError);  }

    function geoSuccess(p) { 
        <% @lat_lng = p.coords.latidude + "," + p.coords.longitude %> 
    }

    function geoError(){ alert("No Location: Won't be able to use Maps functionality"); }
</script>

Something is telling me I need json.

1
  • 1
    BTW, your code has spelled "latitude" as "latidude". Commented Mar 25, 2013 at 3:37

1 Answer 1

13

You are not understanding where and when code runs.

Ruby (on Rails, or otherwise) runs on the server. It creates the HTML+JS+whatever that gets sent over the Internet to the client.

The client (web browser) receives this code and, among other things, executes JavaScript code.

You cannot, therefore, have your Ruby variables be set as the result of running JavaScript code…without contacting the web server again.

You need to use AJAX (or some other, lesser technology) to send a request back to the web server when that function is called.

For example (using jQuery's jQuery.post):

function geoSuccess(p){
  $.post('/newcoords',{lat:p.coords.latitude, long:p.coords.longitude});
}

and in some controller somewhere:

def newcoords
  @lat_lng = [params[:lat],params[:long]].join(",")
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that awnsers my question.

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.