0

I have a Person model whose location is updated every few seconds from a mobile app and saved to the database. Now I want to access the updated information in the view without re rendering the whole page.

How do I do that?

I want to do something like this

setInterval(function(){
  // display updated data
}, 5000);

p.s.: I am using JavaScript only for the time interval, this is a Rails question.

Reloading the page after every few seconds works but totally kills what I'm trying to do.

SRack
  • 11,495
  • 5
  • 47
  • 60
  • 1
    Possible duplicate of [Is it possible to refresh partial frequently using Ajax?](https://stackoverflow.com/questions/13988556/is-it-possible-to-refresh-partial-frequently-using-ajax) – CAmador Sep 26 '19 at 09:59
  • A possible use for [ActionCable](https://guides.rubyonrails.org/action_cable_overview.html)? – SRack Sep 26 '19 at 11:27

1 Answers1

0

Get the data with an ajax request. Assume the div you want to update has id current-location you can do...

setInterval(function() {    
  $.ajax({
    type: 'POST',
    url: "/people/<%=@person.id%>/get_location",
    success: function(data) {
      $('#current-location').html(data.location);
    }
  });
}, 5000);

In your routes.rb define a member path

resources :people 
  member do
    post :get_location
  end
end

Then create an action in your PeopleController called get_location and ensure the last lines are something like...

person_location = get_location # some method that returns location
render json: {location: person_location}
ejuhjav
  • 2,660
  • 2
  • 21
  • 32
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53