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.
JavaScript is a very popular programming language used in lots of projects, also those in Ruby on Rails.
erb view file that generates the actual JavaScript code that will be sent and executed on the client side.
Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.
remote: true is really just telling the browser to not refresh the page. Do the action that you would normally do, but don't do anything to the page.
Send an Ajax call
$(".edit").click(function(){
if ($(this).hasClass("update")){
$.ajax({
type: "PUT",
url: "/sections/<%= section.id %>"
});
} else {
//do something else
};
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With