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.
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
Reset to default 18Send an Ajax call
$(".edit").click(function(){
if ($(this).hasClass("update")){
$.ajax({
type: "PUT",
url: "/sections/<%= section.id %>"
});
} else {
//do something else
};
})
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) {
....
}
});