Sending a JavaScript variable to a Ruby on Rails controller for passing it to an API for further processing

My index.html file contains a Google API map implementation.

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
</style>
</head>
<body>
<div id="map"></div>
<script>
  // Note: This example requires that you consent to location sharing when
  // prompted by your browser. If you see the error "The Geolocation service
  // failed.", it means you probably did not give permission for the browser to
  // locate you.

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 15
    });
    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }



    </script>
    <script async defer
src="https://maps.googleapis.com/maps/api   /js?key=AIzaSyBNvjq57_K8vPYRKETMN6bDogqCpRvBoA0&callback=initMap">
    </script>
    </body>
    </html>

I am looking to use the variable "pos" in my Ruby on Rails controller, specifically in the products controller.

require 'rubygems'

    require 'httparty'

    class ProductsController < ApplicationController



def index

    @results = HTTParty.get("https://api.uber.com          /v1/products?server_token=xyz&latitude=37.7759792&longitude=-122.41823").parsed_response

   respond_to do |format|
   format.json { render :json => JSON.parse(@results) }
   format.html { render "index.html.erb" }
   end
   end
   end

I want to dynamically pass latitude and longitude values in the API URL instead of hardcoding them manually. Any suggestions on how I can achieve this?

Answer №1

According to @max, another request to a controller must be made. If utilizing jQuery and aiming to execute an AJAX request, the process can be achieved in this manner:

$.ajax({
  method: "POST",
  url: "items/some_method",
  data: { lat: position.lat, lng: position.lng }
})
.done(function( response ) {
  alert( "Task completed" );
});

refer to http://api.jquery.com/jquery.ajax/

Additionally, within your ItemsController, include the following:

def some_method
  # perform actions using params[:lat] and params[:lng]
end

Answer №2

solved the issue in question by utilizing params in the windows.open JavaScript function and retrieving those params in the products controller

index.html:

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
</style>
</head>
<body>
<div id="map"></div>
<script>
  // Code for initializing Google Maps and fetching location data

    </script>
    <script async defer
src="https://maps.googleapis.com/maps/api   /js?key=YOUR_API_KEY_HERE&callback=initMap">
    </script>
    </body>
    </html>

products controller:

require 'rubygems'

    require 'httparty'

    class ProductsController < ApplicationController



def index
    lat = params[:lat].to_s
    long = params[:long].to_s
    @results = HTTParty.get("https://api.uber.com/v1/products?server_token=your_server_token&latitude="+lat+"&longitude="+long).parsed_response


   respond_to do |format|
   format.json { render :json => JSON.parse(@results) }
   format.html { render "index.html.erb" }
   end
   end
   end

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

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

A comprehensive guide on implementing filtering in AngularJS arrays

I am working with the array provided below: [ { Id: 1, Name: "AI", Capacity: 2, From: "2021-10-27T08:00:00", To: "2021-10-27T08:50:00", }, { Id: 2, Name: "TEST", Capacity: 2, ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

What is the best way to implement a sidebar closing animation?

Utilizing both react and tailwindcss, I successfully crafted a sidebar menu that elegantly appears from left to right when the user clicks on the hamburger icon. However, my attempts to create a reverse animation as the sidebar disappears from right to lef ...

When an object is not empty, the function Object.getOwnPropertyNames will still return an empty array

In my code, I am filling $scope.master with data from a csv file. When I populate $scope.master within the function, all the data is present. This can be observed in the log output displayed below. However, outside of the function, although $scope.master ...

Is there a way to optimize Typescript compiler to avoid checking full classes and improve performance?

After experiencing slow Typescript compilation times, I decided to utilize generateTrace from https://github.com/microsoft/TypeScript/pull/40063 The trace revealed that a significant amount of time was spent comparing intricate classes with their subclass ...

Creating components in reactjs using the render function

Just a quick query – I've been diving into react js recently. Typically, when we create a component in React, we include the HTML template within the render function. I've noticed that most examples consist of small components with minimal HTM ...

changing the name of a variable within ng-include

Here is some important HTML code: <ng-include src="'app/views/order.html'"></ng-include> Within the scope of this ng-include, there is a variable called trade. The structure of the trade variable is as follows: var trade = { or ...

Allowing several text fields to be paired with multiple checkboxes through a unified jQuery function

I have 4 different checkboxes, each one corresponding to a specific text box. I want to enable the disabled textbox when its corresponding checkbox is checked. Currently, I have written a function for each checkbox in the HTML tag itself using onclick="doc ...

Update the text using JavaScript to modify the price range dropdown when the user clicks away

Dropdown functionality is working when selecting a price, but updating the price in the text box manually does not trigger an update. How can you implement an onblur change event for manual entry of prices? JSFiddle function nFormatter(num, digits) { ...

Error in SO Embed Snippet Fiddle due to Bootstrap 4 JS Issue

Just wondering, any idea why the bootstrap 4 js is throwing this error: https://i.sstatic.net/J4Iq4.png when trying to embed the snippet? (No errors in the external Fiddle) Added tether.js but no luck (kept it commented). Switched to jQuery 2.2.1 on th ...

How can I enhance a JavaScript Calendar with more features?

I recently acquired a JavaScript and jQuery calendar from CodeCanyon, which can be found here. I am now faced with the task of integrating this calendar into my workplace website. The current calendar on our ASPX-based site is limited to read-only functio ...

What could be causing the malfunction in one of the functions within my JavaScript code?

As a JavaScript beginner, I am currently working on creating a To-do App with JavaScript. Most of the functions are functioning perfectly except for one called doneTask at line 36. Despite numerous attempts to identify the issue, I have been unsuccessful s ...

React: Issue with array rendering order after initial render

After the initial rendering of my array in the correct order, any subsequent changes to it result in the same rendered order. Let's consider this scenario: initializeArray() { this.state = { test_array: [1,2,3,4] } let self = t ...

Creating a mat-tree component in Angular Material 6.0.1: Step-by-step guide

I am encountering an issue with my material angular mat-tree based application. The code runs without errors, but the values are not displayed on the screen. I need help resolving this problem so that I can proceed with the development. Upon opening the a ...

In Javascript, merge two arrays together in a specific format

Can we transform two arrays into a specific format so I can create my D3 graph? Here are the two arrays I have: date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"] likes = [2,4,5] I need to convert them to this format: [{ date: '...', lik ...

Guide on showing string array values in an alert popup using JavaScript

I am struggling to display a string array in a JavaScript alert popup. The goal is to show the string index or Serial Number, followed by a space and then a line break before displaying the value of each string in the array. Unfortunately, my current code ...

Transferring the output of a function to a different state

My current challenge involves sending data from one controller to another within an Ionic application. Despite creating a service for this purpose, I am still unable to share the data successfully. The send() function in MainCtrl is meant to pass the data ...

Node.js has no trouble loading HTML files, however, it seems to encounter issues when trying to

Having a bit of trouble with my JavaScript skills as I try to load my index.html file (seems like it should be the 5th easiest thing to do in JavaScript). Let me get straight to the point; when I manually open my index.html, it loads perfectly WITH the CS ...

Universal customization for Material-UI Select

I am attempting to customize the appearance of a select component within a React project using MUI 5. Specifically, I want to modify the border size and color when the select component is in focus. While other components can be styled globally using styleO ...