Michael Durrant
Michael Durrant

Reputation: 96484

How can I pass an id from js to rails when using ajax?

How can I call a rail route and pass in an ID from js.

I am switching to using rails routes through my application including in js

I have a call:

# app/assets/javascript/verifying_link.js
$.ajax({
  url: "/verify_link/"+id+"&table_row="+row,

but I want to use

# app/assets/javascript/verifying_link.js.erb

but how can I pass the id from js ?

I tried:

url: "<%= Rails.application.routes.url_helpers.verify_link_path(id) %>" + "&table_row="+row,

but I get an error:-

undefined local variable or method `id' for#<#<Class:0x00000001ca3220>:0x007f6228c792f0>
(in /...linker/app/assets/javascript/verifying_link.js.erb)

Upvotes: 2

Views: 2891

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

  1. Insert it into the link
  2. Pass it as data

--

Route

As you've attempted already, you could pass it in the route itself:

# app/assets/javascript/verifying_link.js
$(document).on("click", ".element", function(){
   $.ajax({
     url: "/verify_link/"+id+"&table_row="+row
   });
});

The way to do this is to include the id from your HTML.

Your ajax will no doubt be triggered by an event. The event will correspond to an HTML element, which can now have data, or id attributes (thanks to HTML5):

#app/views/controller/view.html.erb
<%= link_to "Your Link", path_to_link, id: @item.id %>

#app/assets/javascript/verifying_link.js
$(document).on("click", ".element", function(){
   var id = $(this).attr("id");

   $.ajax({
      url: "/verify_link/"+id,
   });
});

You'd need to make sure you pass the data to JS from HTML to make this work


Data

Alternatively (and this will only work on collection routes), you could send the id in the data tag. Of course, this will not do anything to help you include your id in your JS, but it's still very important:

#app/assets/javascript/verifying_link.js
$(document).on("click", ".element", function(){
   var id = $(this).attr("id");
   $.ajax({
      url: "/verify_link",
      data: { id: id }
   });
});

The difference here is that if you wanted include other data, you could include it in the data attribute. Further, you'll want to make sure that your routes correspond to what you're looking to send as data (IE member routes will need to have the id appended to the URL)

Upvotes: 6

Alexander Shlenchack
Alexander Shlenchack

Reputation: 3869

You cannot access to Rails values direct in js files. You can pass value in url or create hidden block in you view. Then you can read these values.

Upvotes: 0

Related Questions