Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Rails action from Javascript

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.

like image 303
Ryan King Avatar asked Apr 09 '13 05:04

Ryan King


People also ask

Can you use JavaScript with Ruby on Rails?

JavaScript is a very popular programming language used in lots of projects, also those in Ruby on Rails.

What is a JS Erb file?

erb view file that generates the actual JavaScript code that will be sent and executed on the client side.

What is Rails ujs?

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.

What is remote true in rails?

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.


1 Answers

Send an Ajax call

$(".edit").click(function(){  
  if ($(this).hasClass("update")){     
    $.ajax({
      type: "PUT",
      url: "/sections/<%= section.id %>"
    });
  } else {
    //do something else 
  }; 
})
like image 146
Srikanth Jeeva Avatar answered Sep 28 '22 20:09

Srikanth Jeeva