11

I have the this link_to in my that calls the update action in my controller:

<%= link_to((image_tag("lock_closed.svg", :class => "edit")), :controller => "sections", :action => "update",:id => section.id, :remote => true) %>


But I would really like to call the update action through some javascript with an ordinary image tag.

So something like:

<%= image_tag("lock_closed.svg", :class => "edit")%>

and:

$(".edit").click(function(){
    if ($(this).hasClass("update")){
    // call update action
    } else {
    //do something else 
    };
})

Is it possible to call an action this way? I've been finding a bit on using GET & POST or Ajax methods but I'm not sure how to utilise them to target a specific controller & action.

2 Answers 2

18

Send an Ajax call

$(".edit").click(function(){  
  if ($(this).hasClass("update")){     
    $.ajax({
      type: "PUT",
      url: "/sections/<%= section.id %>"
    });
  } else {
    //do something else 
  }; 
})
Sign up to request clarification or add additional context in comments.

Comments

0

In order to solve the issue of ActionController::InvalidAuthenticityToken on the ajax call we should send also the authenticity_token.

 $.ajax({
   url: '/sections',
   data: { authenticity_token: $('[name="csrf-token"]')[0].content, 
           id: <%= section.id %> },
   method: 'POST',
   success: function (res) {
     ....
  }
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.