0

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!

3 Answers 3

1

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!"
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.