How do I prevent an AJAX link from being clicked twice?

I have a link that I want users to click when they “like” a POST. It’s implemented using AJAX and looks like this:

First thing to note – I never use the Rails remote helpers. They are nice and easy to get started but you lose a lot of control. And if you use JQuery (or Zepto) it’s really simple to do the same thing, but with much more control.

I would do the following:

So we are writing the link out by hand, giving it a HREF of our Rails path and giving it a class of “like-link”.

Then we define an event handler for clicks on any “like-link” (this is Coffeescript but should be easily translatable to Javascript:

So the first thing we do is register a click-handler for all links of class “like-link”. When it’s clicked we disable the browser’s default event handling. Then we store a reference to our link, hide it (so it can’t be clicked twice) and then do an AJAX call to the HREF of our link. When we get a successful response, we make the link reappear.

Nice and easy, with lots of control (including error handling if you use $.ajax instead of $.post).

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe