简体   繁体   中英

Ruby/Rails/AJAX/JQuery - On link click, passing a parameter and performing a controller action

I'm trying to use clicking a link to perform and action in my controller called 'yes' but do so client side rather than having to refresh everytime a user clicks.

Before I had an link_to that routed to a action called "yes" and passed the id of a model I have called 'event'

      <%= link_to "yes", yes_path(event)%>   (in view)

      match 'user/:id/yes' => 'user#yes', :as => "yes"   {in routes.rb)

The problem issue is that every time the user clicks the link the page refreshes while it performs the yes action, so it will flow alot smoother if I can tell the backend to perform the actions client side.

S0 I found a reference here : execute controller/action from javascript in rails3

and took a look at the documentation : http://api.jquery.com/jQuery.ajax/

And came up with this. Where if the post is successful at the previous route from above change a css class for the link (change color).

 $.ajax({
       type: "POST",
       url: "/user/" + $(this).attr('event') + "/yes/",
       success: function(){
           $(".like").click(function() {
           if ($(this).hasClass("selected")) {
           $(this).addClass("selected");
           return false;  } 
    });

I also added this is the bottom of the controller that the desired javascript is being used.

respond_to do |format|
     format.html { }
     format.js
end

So now my link_to looks like this

 <%= link_to "yes", yes_path(event), :class => "like", :remote => true %>

But the page is still refreshing and It doesnt look like its calling the AJAX at all.

  • am I passing the parameter "event" properly as a jquery attribute?
  • am I calling the link_to properly? This is my first time so I have no idea what I'm doing wrong, possibly a few things?

I'd really appreciate any help

Is this what you're after?

$(".like").click(function(evt) {
    evt.preventDefault();

    var $self = $(this);
    $.post($self.attr("href"), function(response) {
        $self.addClass("selected");
    });
});

The first line binds the JavaScript to all elements with a class of like . preventDefault is the preferred way to prevent the default behavior of an anchor tag (navigate to the href). $.post() is shorthand for $.ajax({ type: "POST" }) .

Whatever you want to happen after a successful post to the server goes that finally function call. The first argument is the response from the server.

Rich

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM