Derptacos
Derptacos

Reputation: 177

Display updated data with ajax in rails

I have a static_pages_controller with a home method.

On the home.html.erb page I have a button:

<%= button_to "Refresh recommendations",  
{action: :home, reset: true},method: :get,remote: true , class: 'btn btn-success'%>

When a user clicks the button I want have the controller recompute a list of recommendation, this is working, the issue I am having is updating the div containing the list of new recommendations.

static_pages_controller#home

def home
 puts "PARAMS #{params}"

 respond_to do |format|
   format.html{}
   format.js 
 end
end

From various guides and thread I've been following that I should have a home.js.erb and from my understanding when the ajax call is made the controller should execute home.js.erb - it currently is not executing.

I've included my routes.rb just incase something is messed up.

root "static_pages#home"
post '/spec', to: "static_pages#spec_rec"

When submitting the ajax request the server will outputs the following:

Started GET "/refresh" for 127.0.0.1 at 2014-03-13 12:11:27 -0400
Processing by StaticPagesController#refresh as JS
Rendered static_pages/_refresh.html.erb (0.1ms)

Upvotes: 0

Views: 44

Answers (1)

Danny
Danny

Reputation: 6025

In your routes file, you should have something like

  get 'home/refresh', to: 'home#refresh'

In your home controller you should have

def refresh
  render partial: 'refresh'
end

You should make a partial _refresh in your view home folder, containing the refreshing html

In your view

<%= button_to "Refresh recommendations", refresh_home_path, remote: true, class: 'refresh btn btn-success', type: :html %>

and

javascript:
  $(document).ready(function() {
    $(document).on('ajax:success', ".refresh", function(evt, data, status, xhr){
      $(selector for your div).html(data);
    });       
  });

That should do the job!

Upvotes: 1

Related Questions