user3754124
user3754124

Reputation: 249

Rails - call controller from javascript

Extreme rails nooby here. I am trying to do a simple call to a controller from a javascript file and am fairly stuck, research says I need a ajax request. Can you guys point me in the right direction?

Here is my controller - It simply returns a boolean

class ReferredFriend < ActiveRecord::Base

def refer_email_exists(email)
/return a boolean

Here is my javascript - obviously incorrect syntax, but you get my general idea

if ReferredFriend.refer_email_exists(message.get('to_email')) == 'true'
  alert "That email already exists!"

the route to the controller is: app/models/referred_friend.rb

I put this in my routes file, however I'm guessing this is incorrect as well

resources :referred_friends do
  get :refer_email_exists
end

Thanks for your help!

Upvotes: 0

Views: 100

Answers (3)

animatedgif
animatedgif

Reputation: 1109

Rails provides button shortcodes for remote actions like calling a Rails controller action VIA AJAX. From the Rails docs http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#link-to

link_to is a helper that assists with generating links. It has a :remote option you can use like this:

<%= link_to "an article", @article, remote: true %>

which generates:

<a href="/articles/1" data-remote="true">an article</a>

You can bind to the same Ajax events as form_for. Here's an example. Let's assume that we have a list of articles that can be deleted with just one click. We would generate some HTML like this:

<%= link_to "Delete article", @article, remote: true, method: :delete %> and write some CoffeeScript like this:

$ -> $("a[data-remote]").on "ajax:success", (e, data, status, xhr) -> alert "The article was deleted."

Upvotes: 0

brunozrk
brunozrk

Reputation: 783

The way to do want you want is make a ajax call to your route, something like:

$.ajax({
  url: "<url route to refer_email_exists>",
  success: function(result){
  // check result then
  alert "That email already exists!"
  }
});

Upvotes: 1

user2545521
user2545521

Reputation: 63

What about simple AJAX call?

$.ajax({
    url: Routes.test_email_path(email),
    type: 'POST'
}).done(function (data) {
    // handling success
}).fail(function (data) {
    // handling failure
}   

Where Routes is from js-routes gem.

Upvotes: 0

Related Questions