Using JavaScript values within erb code

In my coding dilemma, I have a js.erb template housing this snippet:

var latlng = new google.maps.LatLng(<%= session[:lat] %>, <%= session[:lng] %>);

But now, I'm attempting to tackle the reverse task (embedding javascript into ruby):

<% session[:lat] = javascript_tag("document.write(location.lat());") %>

Answer №1

The essence of Javascript is escaping your notice.

Your Ruby code (identified by the <% .. %> segments in your examples) operates on the server.

In contrast, Javascript code (

var latlng = new google.maps.LatLng(10, 20);
and document.write(location.lat());) runs within the browser.
This execution occurs after the ruby code, once the server has handled the request and produced the resulting page.

If you wish to access the value of location.lat() on the server, you must transmit it from the browser via an AJAX request. Utilizing any well-known Javascript library will simplify this task.

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

How can the label value be updated in a material ui slider component?

code snippet: https://codesandbox.io/s/runtime-worker-kxse3?file=/src/App.js Can anyone help me ensure that the labels in the bubble display the same values as the text (3, 5, 7, 10)? ...

Achieving a sticky scrollbar effect in CSS/JavaScript for scrolling within nested divs

I am trying to create a table with vertical scrolling for the entire table content. Additionally, I need two columns within the table to be scrollable horizontally, but the horizontal scrollbars disappear when the vertical scrollbar is present. How can I k ...

I am having issues installing mongoid_slug in Rails 4 with Mongoid

I recently began a new project and installed mongoid. However, I encountered an error when trying to install mongoid_slug. I did not use the --skip-active-record option. Bundler was unable to find compatible versions for the gem "mongoid": In the Gemfi ...

Looking for a way to easily swipe through videos?

My mobile phone viewport displays a series of pictures and videos, with the swipeleft/right function enabled for browsing. However, I noticed that while the swipe feature works fine for images, it stops functioning when a video is displayed. Can anyone p ...

Textfield with predictive text suggestions

I am currently working on implementing an autocomplete textfield for my Rails application, following the example from the Agile Web Development with Rails, 3rd Edition. However, when I try to insert their demo code: <%= stylesheet_link_tag &apo ...

Is nextJS SSR the optimal solution for handling undefined variables in the window object to enable optional chaining in cases where global variables are not supported?

When using (window?.innerHeight || 420) for server-side rendering (SSR), the translation would be (((_window = window) === null || _window === void 0 ? void 0 : _window.innerHeight) || 420) However, this could result in a referenceError: window is not d ...

Controlling factory JSON data with $http calls using two separate controllers

I'm attempting to retrieve a JSON response from a factory, save it as a variable, and make it accessible from two different controllers. Below is the code I am utilizing: storyFactory.js var story = angular.module('story.services', []); ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

Showcase your skills in CSS, HTML, and Javascript

I attempted to search for something similar but came up empty-handed. I have two buttons. When I click one of them, I want to hide a certain division, but it's not working as expected. The divs d2 and d3 are initially hidden when the page opens, whic ...

Direct attention to the modal display

I'm having trouble auto-focusing an input field when a modal is displayed. Here's what I've tried, but it doesn't seem to be working: jQuery(document).ready(function($) { $('#myModal').on('show.bs.modal', functi ...

Ember - connecting to a JSON data source

Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...

Checking if a variable is true with jQuery

Check out this snippet of code: <main class="ok">My text</main> <script> $(document).ready(function() { if ( $('body').not('main.ok') ) { // or if ( Boolean ( $('main.ok') ) == false ) { ...

Multer can handle the uploading of various files from multiple inputs within a single form

I've searched everywhere on the internet, but I can't seem to find a solution that matches my specific issue. As someone new to Node.JS, I'm attempting to upload two different pictures using Multer from the same form. Here's what my for ...

Reviewing the element names in a jQuery-selected array of objects

I'm new to javascript and the jquery library and I need to work with an array of input fields that have specific names for validation. Each input field is named NS[0], NS[1], etc., and the total number of these fields is generated dynamically in the c ...

Running a script within an Ajax-rendered form using remote functionality in a Ruby on Rails

After clicking the following button, my form is rendered: = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true The form is rendered using the script below ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Revamping the vertices and UVs of DecalGeometry

I am currently experimenting with ThreeJS decals. I have successfully added a stunning decal to my sphere. Below is the code snippet I am using to place the decal on my sphere. (Please disregard any custom classes mentioned in the code.) // Creating the ...

The `as` value does not match the `href` value error has occurred in next.js

I currently have three main pages on my website: home/start, which directs to home/users/[type], leading to home/settings/[type]. The page for home/start includes the following code snippet: import { useRouter } from 'next/router'; const Start ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...