i have button on home page trigger ajax can see form on home page when button pressed. works 2 of buttons not third , can't figure out why? when press button redirects root, presumably because using '#'. trigger correct ajax (see below) - know console response ajax success. if change url in ajax controller/new new form correctly shown in home page. looks though controller action being directed root reason don't understand
here's button
<div class="col-md-4"> <%= link_to image_tag("arrow.jpg"),'#', id: 'challengelistbutton'%> <div id="challengelistcentre"></div> </div> here's ajax triggers (in application.js)
$(document).ready(function(){ $('#challengelistbutton').click(function(e){ $.ajax({ type: 'get', url: "challenges/index", success: function(response){ console.log(response) $('#challengelistcentre').html(response); } }) }); }); here's controller challenges_controller.rb
class challengescontroller < applicationcontroller before_action :set_challenge, only: [:show, :edit, :update, :destroy] # /challenges # /challenges.json def index @challenges = challenge.all render :layout => false end end here's views/challenges/index.html.erb
<%= render 'index' %> <%= link_to 'back', challenges_path %> and partial:
<p id="notice"><%= notice %></p> <h1>listing challenges</h1> <table> <thead> <tr> <th>pointsspend</th> <th>rules</th> <th colspan="3"></th> </tr> </thead> <tbody> <% @challenges.each |challenge| %> <tr> <td><%= challenge.pointsspend %></td> <td><%= challenge.rules %></td> <td><%= link_to 'show', challenge %></td> <td><%= link_to 'edit', edit_challenge_path(challenge) %></td> <td><%= link_to 'destroy', challenge, method: :delete, data: { confirm: 'are sure?' } %></td> </tr> <% end %> </tbody> </table> <br> <%= link_to 'new challenge', new_challenge_path %> and routes:
rails.application.routes.draw resources :challenges, only: [:new, :create, :show, :index, :edit, :destroy] resources :entries resources :conversations, only: [:index, :show, :destroy] member post :reply post :restore post :mark_as_read end collection delete :empty_trash end end resources :messages, only: [:new, :create] '/messages/new/:id', to: 'messages#new' root to: 'users#index' devise_for :users '/users/relations', to: 'users#relations' post '/users/create', to: 'users#create' resources :users end
you need use preventdefault(), try this
$(document).ready(function(){ $('#challengelistbutton').click(function(e){ e.preventdefault(); // add line $.ajax({ type: 'get', url: "challenges/index", success: function(response){ console.log(response) $('#challengelistcentre').html(response); } }) }); }); hope helps!
Comments
Post a Comment