aminhs aminhs - 1 year ago 48
Ajax Question

Link_to and ajax request in Rails 4

I have the following:

<%= link_to "Some_link", some_path, class: "btn btn-success btn-xs", id: "contact", "data-sid" => %>

In my application.js I have:

$('#contact').click(function (e) {

var item_id = $(this).data('sid');

type: 'GET',
url: '/somepath'+ item_id,
success: function(data) {


error: function() {
window.alert('Error Loading Item!!');

The path "some_path" will have a form for the user to complete. Saying that, what I really want to achieve is when user click the link "Some_link", the link can redirect the user to "some_path" but before that I want to perform the ajax request to load data into the form. I do not know if I can use :remote=>"true" in this case. What is happening now is that when I click the link the ajax works but it is not sending me to the page.

What am I doing wrong? Any suggestions.
Thank you in advance.

Answer Source

Ok now I understand your requirement a lot better, I feel I am more able to help you. You have very much overcomplicated things and the way you are trying to solve this just will not work.

The way it stands at the moment $('#contact').click(function (e) is capturing the click event and then attempting to do the AJAX query - I assume your are sending back the data from your controller and not doing any rendering from that. You receive the data and then attempt to populate the form fields, but of course those form fields don't exist ... you haven't navigated to that page - quite likely your jquery at this point is failing silently.

Now because you have swallowed the event and prevented the default behaviour the original path of your link is not followed. Even if you allowed the event to propagate it would not work as highlighted in the previous paragraph.

Ok, without knowing what your further requirements are, to me it seems all you need to do is

  1. remove all that jquery.
  2. Allow the link_to to just hit your action as a normal HTTP GET.

    <%= link_to edit_item_path(item), class: "btn btn-success btn-xs", id: "contact" %>

    ** assumes you have an ItemController with an edit action and that the routing is setup as

    edit_item GET /items/:id/edit(.:format) items#edit

  3. Set your data as an instance variable in your controller

    @item = Item.find(params[:id])

  4. Render the form as html.erb using the instance variable -

For example,

<%= form_for @item, url: item_path do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <input type='submit'/>
<% end %>

Just a straightforward navigation to a form.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download