Utilizing Rails to gather and display JSON data in a Highcharts visualization

Trying to display custom labels on Highcharts column chart x-axis.

The chart currently renders data, but default labels like 0,1,2,3... are displayed on the x-axis.

notes_controller:

def dashboard
  @data = Note.getData()
end

note.rb

def self.getData
    data = []
    self.subject_types.each do |type|
      data << self.type_count(type)
    end
    data
  end

private

  def self.subject_types
    pluck(:subject_type).uniq
  end

  def self.type_count(type)
    where(subject_type: type).count
  end
end

dashboard.html.erb javascript

...series: [{
           name: 'Number of Notes By Class Module',
           data: <%= @data %>
          }]...

Everything is working fine, but how can I get the labels to show up from a specific column in my table named "subject_type"? I tried the following:

note.rb:

def self.getSubjects
    respond_to do |format|
    render :json => @note.to_json(:only => [:subject_type])
end

(I'm unsure if this approach is correct!)

notes_controller.rb:

def subject
    @subject = Note.getSubjects()
end

dashboard.html.erb:

...series: [{
               name: 'Number of Notes By Class Module',
               data: <%= @data %>, <%= @subject %>
              }]...

Any assistance with this would be greatly appreciated.

Answer №1

What is the reason for wanting to display subject_type on the x-axis? Typically, chart axes are used for measuring data and can be linear, logarithmic, datetime, or categorical.

Based on my interpretation, you want to represent each subject_type as a series name.

If the answer is No, consider this alternative:

xAxis: {
    categories: '<%=raw @subjects.to_json %>'
}

If the answer is Yes, then refer to the following:

Highcharts series object is an array that can contain multiple series. The name attribute defines the series name, while the data attribute represents the series values.

This implies that our series should look like this:

series: [ 
          {name: 'Subject Type 1', data: [5] }, 
          {name: 'Subject Type 2', data: [6] }, 
          {name: 'Subject Type n', data: [n] }, 
        ]

Within your database, there is a Note table with a subject_type column. Each note must have a corresponding subject_type. The unique subject_type will serve as the name of the series, while the total count of that subject_type will be the data for the series.

To achieve this, you can follow these steps:

def dashboard
  @series_data = []
  @notes = Note.select("id, subject_type, COUNT(*) AS total").group("id, subject_type")
  # Collect series data to display
  @notes.group_by(&:subject_type).each do |k, v|
    @series_data << { name: k.titleize, data: [v.size] }   
  end
end

In your dashboard.html.erb:

series: <%=raw @series_data.to_json %>

Additionally, it appears that you require a chart title. You can add it using the following method:

title: {
  text: "<strong>Number of Notes By Class Module</strong>"
}

I trust this information proves to be beneficial in your task.

Answer №2

Give this a try:

To start, utilize your existing class method to generate an array of subject_types:

def dashboard
  @data = Note.getData()
  @subjects = Note.subject_types
end

Next, as demonstrated in Highchats' example, the xAxis: categories json key is where we insert the subjects array of labels:

$('#container').highcharts({
  chart: {
    type: 'line'
  },

  //other options ...

  xAxis: {
    categories: <%= @subjects %>
  },

  series: [{
     name: 'Number of Notes By Class Module',
     data: <%= @data %>
  }]
});

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

Sending JSON data from an Android client to a WCF service for storage in a SQL Server 2008 database

I've encountered an issue while trying to post data through a WCF service. The service is hosted and functioning correctly with my .NET website, but for some reason, it's not working with my Android client. I'm having trouble understanding t ...

Tips on configuring AJAX to utilize the POST method instead of GET

I have successfully implemented the following code: $(document).ready(function(){ var ajaxRequest; // The variable that enables Ajax functionality! try { // Modern browsers like Opera, Firefox, Safari ajaxRequest = new XMLHttpReq ...

What is the process for triggering an exception?

I have a specific function that converts a two-dimensional array into CSV format. The key requirement is that the function only supports text and numbers, triggering an error message for any other input types. Currently, when I execute the function, it s ...

Engage - experiment with incorporating writing functionality for List[Any]

In my project, there is a case class defined as follows: case class A(name: String, values: List[Any]) The "values" field can contain elements of type Long or String. I have been attempting to create a Writes implementation without any luck. Below is th ...

Searching for the subsequent location in a 2D array relative to the current position

Let's imagine we have a 3x4 array: const arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]. If we provide the input as ["straight", "right", "left"], the starting position being arr[0][0] and initial direction as "east". ...

Repair the masthead background during overscroll

The Dilemma At the top of my webpage, I have a sleek masthead with a captivating background image that scrolls along with the page. However, there is an issue when users overscroll upwards, causing an undesirable white overflow to appear. To rectify this ...

Toggle between classes by clicking on the next or back button

Looking to create a multi-step form where the initial step is visible while the rest are hidden using the "hide" class. I want to toggle visibility of each step with Next and Back buttons, displaying only one step at a time. Can someone assist with this? ...

Continual Use of Google Calendar API

Is there a way to request access to a user's calendar once and then continuously query events without needing to request access again? Can an access key be used for ongoing access as long as it remains valid? Currently, I am utilizing the google-cale ...

Slider fade animation not functioning as expected

Why won't the last slide display? How can I ensure that the first image is shown immediately after the side loads, without any delay? I've attempted various solutions but always encountered issues (such as displaying two images simultaneously) an ...

What causes my array of objects to be assigned numbers when copying a JSON data file using Object.assign?

I have a JSON file that I need to transfer to my local object using new Object and Object Assign: let newObj = new Object(); Object.assign(newObj, MyData.map(data => ({ personal_id : data._id, idx : data.index, voiceLines : data.tags }))); console.log ...

The input field will be in a read-only state if it contains a value from the database. However, it will be editable if the value

Hello everyone, I am a newcomer to this community and would greatly appreciate your help. I am encountering an issue with the following lines of code: <input type="text" class="form-control" id="fines" name="fines&quo ...

Is there a way to initiate an animation by clicking on something?

Currently, I have implemented requestAnimationFrame(loop); and I'm aiming to have an onclick button that triggers the animation. The setup involves clicking a button to initiate the animation process. I have the button structure set up as follows: < ...

Having trouble retrieving Yelp Fusion using an express backend

Attempting to retrieve Yelp data within my backend using Express and then saving the data in the state for frontend use has presented a challenge. When making the request, an error is thrown displaying AxiosError: Request failed with status code 400 in the ...

Selenium encountered an error when trying to execute the 'querySelector' function on the document. The selector provided, my_selector, is not recognized as a valid selector

Whenever I run this code: document.querySelector(my_selector) using selenium, an error is thrown: Failed to execute 'querySelector' on 'Document' my_selector is not a valid selector my_selector is definitely a valid selector that func ...

Encounter a critical issue while making a JSON request using Kendo UI

I am facing an issue at my workplace where I need to integrate Angular.js with ASP.NET MVC. Currently, I am trying to build a simple application that features a Kendo UI grid on the front page. In my App.js file, I am fetching data from the Data Controller ...

Enabling Cross-Origin Resource Sharing (CORS) for Tomcat REST API

Recently, I set up a local Tomcat installation on port 8081 to expose a REST API. However, my development web server operates on port 9000. I want to make calls to the REST API from JavaScript code running in the browser using Angular's $http. Due to ...

Is there a way to retrieve JSON data from a child component and pass it to a parent component in Vue.js?

I have data from the results stored in a child component that needs to be passed to the main component. The Main Component is the parent, so whenever I click the button, the results should be collected in the main app <button @click="showFinalResu ...

Tips for Troubleshooting External Evaluation Scripts

For a specific example, take a look at the haystack.js script from How Big is Your Haystack? I've been searching for a solution and it seems that using the //# sourceURL=name.js comment is the way to go. However, I am struggling with the process of a ...

The JavaScript Discord Bot is having trouble connecting to a voice channel

I'm currently working on developing a discord bot using node.js. While I've successfully set it up to respond, I'm facing an issue with summoning it to a voice channel. Here is the snippet of code I am working with: switch (args[0]) { c ...

Tips for transitioning frontend JS to Angular 2 for seamless integration with a PHP MVC backend system

I currently have a robust PHP MVC web application that utilizes jQuery for click events and modal dialog rendering. To align with up-to-date frontend technologies, I am looking to revamp the JavaScript code to function within Angular 2. However, I am faced ...