Accessing information from a database table using Highchart and Ruby on Rails (ROR

I have a Ruby on Rails application that utilizes highcharts. I am currently working on enhancing it to display the amount of time spent on specific projects. To demonstrate what I am trying to achieve, I have created a JSFiddle example which can be found here. My initial goals are as follows:

  • The user logs in to their timesheet, selects one or multiple projects, and enters the hours spent
  • The entered data regarding hours and selected project(s) are then stored in a ProjectsHours table
  • The current user can later view the project hours page, where the information from the ProjectsHours table is extracted and displayed similarly to the provided JSFiddle example

Upon conducting my research, I discovered on the Highcharts website that data can be requested through an Ajax request.

I am reaching out with this question because I am still relatively new to Ruby on Rails and JavaScript.

Furthermore, I have implemented an autocomplete feature using an Ajax request and JSON data retrieval. While slightly unrelated, I am sharing the following JavaScript code for my autocomplete function as I believe it could have similarities to what I am attempting to accomplish. Any corrections or guidance would be greatly appreciated.

Autocomplete

Application.js

function log(message) {
        $( "<div>" ).text( message ).prependTo("#log");
    }

    $("#tags1").autocomplete({
        minLength: 2,
        source: function(request, response) {
            $.ajax({
                url: "/positionlist",
                dataType: "json",
                data: {
                    style: "full",
                    maxRows: 12,
                    term: request.term
                },
                success: function(data) {
                    var results = [];
                    $.each(data, function(i, item) {
                        var itemToAdd = {
                            value: item,
                            label: item
                        };
                        results.push(itemToAdd);
                    });
                    return response(results);

                }
            });
        }
    });  

Answer №1

My preferred method for using AJAX with highcharts involves setting up a setInterval function that fetches data from a JSON file and updates a pie chart:

 setInterval(function(){
  $.getJSON('traffic_sources.json', null, function(data) {
      pie_chart("traffic_sources_graph", data.traffic_sources);
  });
 }, 3000);

function pie_chart(div, data)
{
   new Highcharts.Chart({
      chart: {
         renderTo: div,
         backgroundColor: '#dddddd'
      },
      title: false,
      tooltip: {
         formatter: function() {
            return '<b>'+ this.point.name +'</b>: '+ this.y +' %';
         }
      },
      plotOptions: {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
               enabled: false
            },
            showInLegend: true
         }
      },
      legend: {
         layout: 'vertical',
         align: 'right',
         floating: false,
         labelFormatter: function() {
            return this.name + "(" + this.y + ")";
         }
      },
       series: [{
         type: 'pie',
         name: 'Browser share',
         data: data
      }]
   });
}

The format of the JSON data used in the example above is tailored for a pie chart representation. A bar chart may require slight adjustments to the data structure:

{"traffic_sources":[["Direct",5465465],["Search Engines",345876],["Referring Sites",4578767]]}

I hope this explanation clarifies the process for you.

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

React Native - Issue with array value not reflecting in Text component

import React, {useState} from 'react'; import { FlatList, Text, View} from 'react-native'; import {styles, styleBox} from './components/styles'; import Slider from '@react-native-community/slider'; export default fu ...

Receiving an empty response when utilizing Ajax to fetch a token from an external website

I currently have two websites in operation. One of the sites has a token, while the other is designed to allow a user to utilize this token for certain actions. Upon visiting the first site which contains the token, mySite.local/services/session/token I ca ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...

When comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

Add array as an element within another array

After initializing the data, I have an object structured like this and I am able to push data using the method below: myObj = { 1: ["a", "b", "c"], 2: ["c", "d", "e"], } data: { types: {} }, methods: { pushValue(key, value) { var ...

The dropdown menu in AngularJS is unable to retrieve the selected index

Presently, I have a dropdown menu: <select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;"> ...

Develop a diverse range of form types within Django forms

Even though I know how to create a form set based on a given form type, it doesn't completely resolve the issue at hand. Imagine having a fast food portal where users can add items and depending on their selection, additional fields need to be dynami ...

What is the best way to incorporate a dropdown header in Material-UI on a React project?

I am facing an issue where only the last Menu Dropdown is rendering, but I actually need different Menus to be displayed (with the text faintly appearing behind them). I am uncertain about how to correctly pass the props/state to make this work. import Rea ...

What could be the reason behind getting a useLayoutEffect error when using renderToString to render a Material-UI component?

Currently, I am utilizing React version 16.12.0 along with @MaterialUI/core version 4.8.1. The challenge I am facing involves creating a custom icon for a React Leaflet Marker. The icon in question is a Fab component sourced from Material-UI. In order to ...

(Definition) What is the proper way to reference a variable inside another variable?

Currently, my project is using inconsistent terminology when referring to variables, and I need to clarify this issue. Let's take an object defined in this way: var anObject = { a: { value1: 1337, value2: 69, value3: "420 ...

Error: Unsupported Media Type when attempting to send JSON data from an AngularJS frontend to a Spring controller

Below is the controller function code snippet @RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"}) public @ResponseBody String logInCheckerFn(@RequestBody UserLogData userLogData){ Integer user ...

The current date object in JavaScript will only display the year or a combination of the month and

$scope.articles = [ { link: "http://google.com", source: "Google", title: "hello", "date": new Date(2008, 4, 15) }, ]; <tbody> <tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ...

HTTP GET request not updating data

I'm experimenting with AngularJS and trying out some examples: Here's the HTML code snippet: <html ng-app="myApp"> <body ng-controller="JokesController"> <h1>{{ joke }}<h1> </body> </html> A ...

No files located by the server

My experience with writing a basic express script to serve a webpage with embedded Javascript has been quite frustrating. The server seems to struggle finding the files I provide, and what's even more aggravating is that it sometimes works but then su ...

The issue with the dispatch function not working in the Component props of React Redux

I'm struggling with my colorcontrol issue. I've been attempting to use this.props.dispatch(triggerFBEvent(fbID, method, params)) without success. Interestingly, it seems to work fine if I just use triggerFBEvent(fbID, method, params). However, I ...

Understanding the Functioning of a Digital Analog Clock Using JavaScript

As a new learner, I found the operation of a Digital analog clock to be quite puzzling. I was presented with an image called clock.png, and I specifically struggled with how the hands of the clock function. Javascript - const deg = 6; // defining the valu ...

Extract ID for Bootstrap modal display

In my project, I am using a bootstrap modal that displays various strings. The challenge I am facing involves a loop of cards, each with a distinct 'id'. When triggering the modal, I want to show the corresponding id inside the modal itself, whic ...

Is there a way to retrieve the value from an input box?

<td class="stockQuantity"> <input class="form-control" id="Cart1" name="qty_req" required="required" type="text" value=""><br> <button type="button" o ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...