简体   繁体   中英

Rails - make link work with ajax

I have a link that should use ajax to load a partial next to it without reloading the page. Here is the link:

<%= link_to 'test ajax link', profile_form_path , remote: true %>

Here is the controller that the link should go to:

class ProfilesController < ApplicationController
    def profile_form #the action is currently static so there is nothing in the controller
    end
end

And here is the js view that the controller action goes to:
profile_form.js.erb

$('.tab-edit-profile').html("<%= j render 'profile_form_p' %>");

However, it does not work. The browser returns this error:

Template is missing
Missing template profiles/profile_form

Here is the line in the routes file:

get 'profile_form', to: 'profiles#profile_form'

If I change the file name to profile_form.html.erb, the page loads but not using ajax obviously. Can anyone tell me the correct way to use ajax to implement this? Thanks.

From what you posted above, that should work correctly. The only thing I can think of is that you're not including the required javascript libraries and the link_to helper is not actually making an AJAX request.

You indicated that you're using Rails 4 so I'm assuming you're also using the Asset Pipeline. Please ensure that you have the following lines in your app/assets/javascripts/application.js file

//= require jquery
//= require jquery_ujs

and that the javascript is being included in the layout being used by the ProfilesController . Assuming the layout is application.html.erb , ensure that you have

<%= javascript_include_tag "application" %>

in the <head> section of your layout.

What you need is a partial, for example, _profile.html.erb . The underscore tells Rails this file is rendered as partial. In your profile_form.js.erb you can try.

$('.tab-edit-profile').html("<%= escape_javascript(render 'profile') %>");

That should get you going with static content. For dynamic, setup a @profile instance variable and try.

$('.tab-edit-profile').html("<%= escape_javascript(render @profile) %>");

Be sure to use render json: @profile in your controller response.

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