Pass the ActiveRecord object retrieved in the success of the ajax call in Rails as a parameter to another subsequent

Imagine this scenario: I have a view named "Dashboard" featuring a basic form and a button labeled "Draw Graphs". The goal is to trigger two ajax requests upon clicking the button, fetching the required data from the database for creating two distinct graphs. The catch is that both requests should avoid redundancy by utilizing the same query.

Currently, my approach involves firing a single ajax request when the button is clicked, querying mysql for the necessary data. This retrieved data is then passed as parameters to two additional ajax requests in order to structure the graphs using javascript.

This process can be outlined as follows:

JavaScript:

$('#draw_graphs').click(function() {
    $.ajax({
        url: 'single_query',
        dataType: 'json',
        data: $('#myForm').serialize(),
        method: 'get'
    }).success(function(activeRecord) {
        ajax_graph1(activeRecord);
        ajax_graph2(activeRecord);
    });
});

ajax_graph1 = function(activeRecord) {
    $.ajax({
        url: 'create_g1',
        dataType: 'json',
        data: {active_record: active_Record},
        method: 'post'
    }).success(function(g1) {
        create_g1(g1);
    });
};

ajax_graph2 = function(activeRecord) {
    $.ajax({
        url: 'create_g2',
        dataType: 'json',
        data: {active_record: active_Record},
        method: 'post'
    }).success(function(g2) {
        create_g2(g2);
    });
};

Rails:

def single_query
  result = Data.where("etc... etc...")
  respond_to do |format|
    format.json { render json: result.to_json }
  end
end

def create_g1
  activerecord = params[:active_record]
  graph1 = {}
  activerecord.each do |ar|
    #do whatever with graph1
  end
  respond_to do |format|
    format.json { render json: graph1.to_json }
  end
end

def create_g2
  activerecord = params[:active_record]
  graph2 = {}
  activerecord.each do |ar|
    #do whatever with graph2
  end
  respond_to do |format|
    format.json { render json: graph1.to_json }
  end
end

The issue arises when attempting to pass an active record from the controller to javascript and back to the controller again. It appears that the structure gets altered in the process. While single_query's result belongs to ActiveRecord_Relation class, it transforms into ActionController::Parameters class while passing through the "javascript layer."

Answer №1

Your explanation is logical: it's best to minimize database queries. The challenge lies in grasping the interaction between the "javascript layer" and Rails. When an AJAX call retrieves a JSON representation of an XHR Response object, it corresponds to an active_record representation in Rails but isn't the exact JS object instance.

Given this, focus on handling the record on the Rails side and consolidating responses into one AJAX call. For example, let your $('#draw_graphs').click( AJAX call access a corresponding controller method like def draw_graphs. In this method, execute the DB query, construct each graph, and return both graphs as a JSON hash (as shown below). Then, in the .success(function(graphs), parse the response to utilize the results in your 2 ajax_graph methods.

To format the JSON hash:

format.json { render json: { graph1.to_json, graph2.to_json } }

Additionally, consider design optimizations by keeping the controller lightweight and delegating parameter sanitization/permitting in result = Data.where(...) to a separate class method that handles the query and potentially has a helper function for graph generation. It seems possible to implement a case statement within the helper method for different graphs since the code for create_g1 and create_g2 appears similar. Likewise, there may be room for refactoring in the JS code.

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

Is there a way to connect the select2 plugin to a select element that contains plugin options in a JSON object stored in the data attribute?

Utilizing various select2 plugins, I am looking to set the options and values of the plugin based on the data attributes of related elements. The following is an example: HTML <select data-plug="select2" data-plug-op='{"placeholder":"text1","con ...

What could be the reason behind the successful execution of the Node fs.writeFile() method, yet leading to the browser receiving an empty file?

Here is an example of a callback function that appears to be sending an empty file to the browser, despite the fact that the server actually contains the word 'helloworld': router.get('/Download', function(req, res) { var fs = requ ...

Neither of the peer models is present in the JSON file

Here is a follow-up question related to a previous one about JSON not being nested in a Rails view. In my application, I have a hierarchy of models that are structured as 1:many relationships as they descend. At the second-from-bottom level, there is a mo ...

Unleash the full potential of React and material-ui with the Raised Button feature - find out how to effortlessly keep all

This snippet showcases the code for my custom Buttons component: import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; const style = { button: { margin: 2, padding: 0, minWidth: 1, }, }; cons ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

Copy the AJAX response from a JQuery request to the clipboard seamlessly without requiring the user to manually click a button

I'm attempting to automatically copy a portion of a JSON AJAX response to the user's clipboard. When the user submits a form by clicking a button, I want the response to be copied without any additional interaction required. This is my progress ...

Unable to store data in database using Ajax PHP MySQL

Here is the code from my index.php file: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <form name="form1" method='POST'> <sele ...

Obtain the correct form ID format that is dynamically loaded following the execution of an AJAX function

When adding dynamic HTML elements, it is recommended to use delegation binding. However, I am encountering an issue with getting the proper "id" of the form element. $(document).on("submit", "form#add_education", function(e){ e.preventDefault(); ...

The timing of the JavaScript dialog with the AJAX call is off-kilter

Encountering an issue with a JavaScript script designed to showcase a JQUERY dialog box based on a C# ViewModel. Within a repeater, there is an ASP drop-down menu displaying 'Registration Date' details. The objective is for the JavaScript dialog ...

PHP mail function causing email to be filtered as spam

I've been using this code to send emails, but unfortunately, the emails are ending up in the spam folder. I've tried sending through both Gmail and Hotmail, with the same result. Here's the PHP code: <?php if($_POST) { //check if its an ...

Turn off Satellizer Popup Window Title Bar

Currently, I am implementing the satellizer plugin for Facebook authentication. However, I have encountered an issue with the default popup login window of Facebook, which includes a title bar and menu options. I would like to transform this popup into a m ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

How to efficiently calculate totals in an HTML table using JavaScript/jQuery

I have a gridview that displays product details and includes a quantity textbox that is not linked to any database. For each row, I want it to show the cost (price * quantity) and the total cost for all rows in a label below. However, I am encountering a f ...

The declaration for "Control" is not present, possibly being restricted by its protection level

I'm really struggling to get the jQuery datepicker working in ASP.NET. I've tried various examples, but nothing seems to work for me. Even though I'm fairly new to ASP.NET, I am learning quickly! Here is the script I am trying to use: < ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

What could be causing res.redirect to fail at redirecting the page in a nodejs application?

Why isn't the code res.redirect('/taskswriter') working and not directing to the page? Here is the Express.js code snippet: router.route('/update-sources').get(function(req, res) { User.updateMany({"Addtasks.commonID":req.query ...

What are the steps to handle AJAX POST data and store it in EF Core using .Net Core?

I've been working on this issue for hours and I just need a little nudge in the right direction. My jquery AJAX post is successfully sending the data in the post request, but it always turns up null on the controller side. I've tried adding [From ...

Is there a way to streamline the process of dragging and dropping multiple files with C# selenium automation?

I have successfully implemented code to drag and drop a single image, but I am unsure about the necessary changes needed to support multiple file uploads. Can anyone provide assistance with this? Thank you. driver.Url = "http://example.com"; IWebEleme ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Increase visibility, decrease visibility by utilizing ng-hide/ng-show and functions

As I implement the show more/show less feature, I am uncertain if achieving a smooth effect is feasible. However, I believe it's worth reaching out to this community for some creative ideas on how to make it possible. I have a list of dynamic links w ...