简体   繁体   中英

How to pass javascript variable to rails erb

Ok, I know the answer is AJAX call, but I have a particular problem: Everything happens at my homepage in 2 steps:

1- The main user access the root "/"

2- at my index page I have a JS that get his current location (latitude & longitude) AND reloads the page with the information in hands with NO user interaction - then showing the page correct.

The problem : I don't know how to make an ajax call doing this ( I don't want to reload all the layout doing window.location ), I want just the index.html.erb, got it? But it's too hard man, I'm on this like a month and can't do it :( Please, someone help me, I really need. Thanks a lot.

When you retrieve the current location, you have a callback in Javascript, that tells you that everything is finished. Inside this callback, you have access to the position in Javascript, right?

Then you could just post an AJAX request to a route in your Rails app. For example:

routes.rb

post "/user_position" => "position#update"

position_controller.rb

class PositionController < ApplicationController
   def update
     puts params
     # here store the params in your db, or do whatever you want
   end
end

JS:

function successGeoCallback(data) {
   $.post("/user_position", { lat: data.latitude, lng: data.longitude })
   .done(function(data) {
      alert("Position was stored" + data);
    });
}

You don't need to touch the controller for that. In your erb file, something like this could work:

<script>
  if (<%=params[:geo_location].blank? ? 'true' : 'false' %>) {
    locationData = DO_YOUR_THING_HERE;
    $.get('/', { geo_location: locationData});
  }
</script>

This way, when the page first loads, an ajax request will be sent with the parameters. After the page loads in the second time, the location data will be accessible from the erb file from the params[:geo_location] object.


If you are just willing to refresh a part of the page, you can do something like:

$('#container').load('/A_NEW_CONTROLLER_PATH', {geo_location: locationData});

and set up a A_NEW_CONTROLLER_PATH to return only the partial HTML your interested in. you can do that using render 'index', layout: false in your controller action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM