What is the best way to transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript?

I have recently started using rails routes within my application, even in js.

The current code I am using is:

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

However, I would like to switch to using:

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

But I am unsure how to pass the id from javascript. Is there a way to do this?

I attempted the following:

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

Unfortunately, this resulted in an error:-

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

Answer №1

  1. Place it within the link
  2. Use it as data

--

Route

If you've already tried, you can 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
   });
});

To achieve this, include the id from your HTML.

Your ajax will be triggered by an event associated with an HTML element that now has data or id attributes (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,
   });
});

Ensure to pass the data from HTML to JS for this to function correctly


Data

Alternatively (works only on collection routes), you can send the id in the data tag. This won't help include the id in your JS, but it's still significant:

#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 need to include other data, you can add it in the data attribute. Also, ensure your routes match what you're sending as data (for instance, member routes should have the id appended to the URL)

Answer №2

To access Rails values in JavaScript files, you have a few options. One way is to pass the value through the URL or create a hidden block within your view. This allows you to then retrieve and use these values in your JavaScript code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the potential causes of an asynchronous error in a WebGLRenderingContext?

While running an animation loop, I encountered a peculiar error message that reads... GL ERROR :GL_INVALID_OPERATION : glDrawElements: Source and destination textures of the draw are the same. This error seems to occur randomly after 2 or 3 animation fr ...

I am attempting to expand an array of objects divided into two distinct inputs within a React component

There is an array of objects named estimate, with keys 'cost' and 'service'. By clicking 'Add', a new index (i) can be added to the array. The problem arises on the first cycle where {'cost': 2500, 'service&apos ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

php Ajax call functions correctly on local machine, but fails on server

While attempting to implement a progress bar during script execution, I encountered an issue. The progress bar works correctly in Visual Studio testing, but fails when deployed on a server. Is there a PHP or IIS configuration that might be hindering its fu ...

Is it possible for Vue js to display an image from the /dist/ directory even if it is not present?

Currently, I am in the process of learning Vue.js + webpack and have started a project by following these steps: f:www\> npm install -g vue-cli f:www\> vue init webpack-simple my-project f:www\> cd my-project f:www\> npm in ...

Efficient Communication in JSF Using JQuery MobileAjax

This problem has been causing me endless frustration! After coming across a forum post JSF f:ajax listener not called, I realized that it perfectly describes the issue I'm facing. Currently, I am using JSF 2.0 along with the Jquery mobile extension ...

Strategies for refining the names in the dropdown options using AngularJS

I am working with a select element that has a name and id as options value. I am also adding '-' along with the name. However, there is a scenario where the name will be empty and in that case, the '-' should not be displayed. The expe ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

Swap out the hyperlink text for a dropdown menu when clicked and then revert back

Is there a way to dynamically switch between a label/text and a Kendo Combobox in a div using JavaScript when clicking on the text? The desired functionality includes: Clicking on the text displays the combobox, clicking away from it hides the combobox a ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

Should we employ getAttribute() or avoid it entirely? That is the ultimate query

Similar Topic: JavaScript setAttribute vs .attribute= javascript dom, how to handle "special properties" as versus attributes? On multiple occasions, I've encountered criticism in forums or Usenet about the way I access attributes i ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

Is there a way to verify the presence of any ongoing AJAX requests using jQuery?

Attempting to perform a specific action: var function some_action() { // ... } However, this action must wait for all ajax calls to finish. To address this requirement, I have implemented the following approach: $(document).one('ajaxStop', ...

Struggling to access values from your model using EL in JavaScript? Let me provide some guidance

In my model, there is an object named "domain" with two methods: getDescriptionEn() and getDescriptionFr(). I am trying to retrieve the appropriate description based on the current locale. My issue lies in the following code snippet: var locale = "${cur ...

Ajax - Is utilizing API Endpoints the correct approach?

I am encountering an encoding issue when making an AJAX request to an API Endpoint. The code snippet below shows the Endpoint implementation using Java Spring: @Autowired ApiKeyRepository apiKeyRepository; @RequestMapping(value= "/weather/{cit ...

Leveraging summernote in meteor with Discover Meteor tutorial

Recently, I've been delving into the world of Discover Meteor and encountering some challenges along the way. My current hurdle involves integrating content entered in summernote into mongo, but it seems to be more complicated than expected. The fil ...

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...

Child routes in Angular tabs are failing to display in the currently active tab

Hey there! I'm currently working on navigating my Angular application using tabs, and I've run into a bit of an issue with the child routes. Specifically, when I switch to the second child route within the second tab, the status of the tab change ...

Tips for Making Your Popup Window Stand Out

Looking to design a unique pop-up window featuring three tree-style radio buttons and a single submit button. Upon selecting one of the radio buttons, the chosen value should be recorded in the parent window. ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...