Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Javascript code to create maps overlaid with data.

This is the existing code:

<h1>US Map of Startup Density</h1>

<% i = 0 %>

 <script type='text/javascript'>
   google.load('visualization', '1', {'packages': ['geochart']});
   google.setOnLoadCallback(drawMarkersMap);

   function drawMarkersMap() {
   var data = google.visualization.arrayToDataTable([
    ['Location', 'Startups'],
    <% @locations.count.times do %>
                [<%= "'#{@locations[i].name}', #{@locations[i].d_s}" %>],
         <% i += 1 ;end %>

 ]);

  var options = {
   region: 'US',
   resolution: 'provinces',
   displayMode: 'markers',
   magnifyingGlass: {enable: true, zoomFactor: 9.0},
   colorAxis: {colors: ['green', 'blue']}
 };

  var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  chart.draw(data, options);
};
</script>
</head>
<body>
<h4>All cities with less than 10 startups have been exempted from this graph.</h4>
 <div id="chart_div" style="width: 900px; height: 500px;"></div>

Upon inspection, it's clear that I made the mistake of directly embedding Ruby into JavaScript, which surprisingly worked initially but now poses a challenge for serving this map effectively to users in production mode.

I am exploring different solutions:

  • Considering using the gon gem but unsure about its compatibility with the current complexity of the code.
  • Exploring the possibility of processing the data in JavaScript, although my knowledge in this area is limited, especially when dealing with an ActiveRecord call.
  • Tried disabling the JavaScript asset compiling in 'production.rb', but encountered difficulties. It's possible that I implemented it incorrectly.

Answer №1

To best utilize your Locations resource, consider exposing it as an API and then making an AJAX call to load it as JSON. This allows you to easily extract the data obtained from ActiveRecord by traversing the JSON object.

Modify your LocationsController as follows:

class LocationsController < ApplicationController
   respond_to :html, :json

   def index
      respond_with Location.all
   end

   ...
end

This configuration enables your Locations resource to respond to requests for data in either JSON or HTML formats. If accessing a list of Locations directly from the browser isn't necessary, omit :html from the respond_to method.

Utilize jQuery to retrieve Location data within your JavaScript code:

<script type='text/javascript'>
  google.load('visualization', '1', {'packages': ['geochart']});
  google.setOnLoadCallback(drawMarkersMap);

  function drawMarkersMap() {
    $.ajax({ url: '/locations', dataType: 'json' })
        .done(function(data) {
            // Format the retrieved JSON object according to your needs
        }
    );

     var options = {
      region: 'US',
      resolution: 'provinces',
      displayMode: 'markers',
      magnifyingGlass: {enable: true, zoomFactor: 9.0},
      colorAxis: {colors: ['green', 'blue']}
    };

     var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
     chart.draw(data, options);
};
</script>

The ajax call fetches your Location data in a JS-friendly JSON format. You'll need to further adjust this data to match Google Charts' requirements, but this serves as a solid foundation.

Unless there are additional complexities overlooked, leveraging Rails for such tasks is typically straightforward. It exemplifies one of Rails' strengths in handling scenarios like these.

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

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Error: The function coolArr.printArray is not defined in the npm package being imported

My custom package contains an index.js file with the following code: module.exports = class CoolArray extends Array { printArray() { console.log(this); } } After transpiling the code using es2015 syntax with Babel, I connected the package to my te ...

Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each ...

Is it possible for an Express app.get() function to identify and handle requests for specific file extensions

Is it possible for me to manage requests for any .html file type? For example, can I achieve something like this: // server.js app.get('/*.html', (req, res) => { // perform certain actions when an html file request is made }); ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Communicating with Socket.io using the emit function in a separate Node.js module

I've been trying to make this work for the past day, but I could really use some assistance as I haven't had much luck figuring it out on my own. App Objective: My application is designed to take a user's username and password, initiate a m ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

JavaScript makes it possible to access subnodes in XML by utilizing specific methods and

I am looking to utilize javascript to extract data from an XML file that has been loaded into a webpage. Below is the XML file (a.xml) that I am working with. a.xml <?xml version="1.0"?> <Step rID="T6"> <Obj ><![CDATA[Get Data Ta ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

When setValue is called on VCheckbox in Vuetify, it emits an event called "update:modelValue"

After setting a value for the checkbox, I encountered a warning message: [Vue warn]: Component emitted event "update:modelValue" but it is neither declared in the emits option nor as an "onUpdate:modelValue" prop. Example.vue <script setup lang="t ...

After changing pages, the checkbox's state is reset to empty

I am currently working with an array of objects structured as follows: const columns = [ { key: "Source_campname", title: "TS Camp Name", customElement: function (row) { return ( <FormControlL ...

React and Axios: Overcoming CORS Policy to Connect with Java/SpringBoot REST Backend Service

As a first-time user of Axios to connect to my Java/SpringBoot Rest GET service on localhost:8080, I am using React and node.js. My goal is to successfully retrieve the REST data but encountered the following error: Failed to compile src\App.js Lin ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

The useEffect hook is triggering multiple unnecessary calls

Imagine a tree-like structure that needs to be expanded to display all checked children. Check out this piece of code below: const { data } = useGetData(); // a custom react-query hook fetching data from an endpoint Now, there's a function that fin ...

JavaScript and Ajax are functioning properly in Mozilla Firefox, however there seem to be some compatibility issues with Google Chrome

I have a form that serves the dual purpose of registration and login, and I am using JavaScript Ajax to submit it. While it works smoothly in Mozilla Firefox, it fails in Chrome and IE. The goal is to execute an AJAX and PHP script that checks the databa ...

Guide on transforming a PHP array encoded in JSON into a JavaScript array

After fetching a JSON encoded array via AJAX from a PHP file, I need to manipulate it as an array in JavaScript. How can I achieve this? Here is my AJAX call to the PHP File: $.ajax({ type:"POST", url:"ajaxfetch.php", success:function(re ...

Unexpected issue with PHP/Ajax/JQuery response functionality

I am experiencing an issue with my index.php file. Here is the code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="ajax.js"></script ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...