Reuben
Reuben

Reputation: 711

Run Javascript and Controller Actions Before Page Renders

I have a simple rails app that geolocates the user upon arrival to the site (this code is located in the head tag of my application.html.erb file):

<script>
  var x=document.getElementById("demo");
  function getLocation()
    {
    if (navigator.geolocation)
      {
      navigator.geolocation.getCurrentPosition(showPosition);
      }
    else{x.innerHTML="Geolocation is not supported by this browser.";}
    }
  function showPosition(position)
    {
    var lat = position.coords.latitude;
    var log = position.coords.longitude;
    document.cookie = "cl=" + lat + "&" + log + ";";
    }
  getLocation()
</script>
<p id="demo"></p>

The coordinates get saved as cookies. Based on those coordinates, they're used to retrieve a specific set of data from the DB in my controller. These results then get displayed in the view.

Currently when the user first arrives to the site the page is blank, when the page is refreshed the location information passes through the controller and the appropriate data shows up.

What I am trying to do is have the geolocation and controller actions complete on the initial page load, so the data displays when the user first arrives to the site. Or more simply:

  1. Get coordinates of user's location
  2. Pass coordinates to controller and retrieve data
  3. Then Display data in the view

I think the root of my problem is the ordering of the javascript and controller events, but I'm not sure how to fix this.

Upvotes: 1

Views: 663

Answers (1)

Jakob W
Jakob W

Reputation: 3377

Since the javascript runs in the browser and the page is rendered on the server side you need to either reload the whole page or do some ajax update in showPosition. Otherwise, the coordinates will always be one step behind: If you move to another location the coordinates in the cookie will be from the last location, not the current one.

Upvotes: 1

Related Questions