Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
BTW, your code has spelled "latitude" as "latidude". –  Phrogz Mar 25 '13 at 3:37
add comment

1 Answer

up vote 5 down vote accepted

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
share|improve this answer
    
Thank you, that awnsers my question. –  user2002525 Mar 25 '13 at 3:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.