简体   繁体   中英

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!

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!"
  }
});

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.

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

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