Sending data to a controller using an AJAX request in a Ruby on Rails app

Looking for guidance on passing data through ajax to the controller. The page where I have this setup is /admin/projects/report_project_resources.html.erb

<%= select("project", "report", Project.where(closed: false).collect { |p| [ p.name, p.id ] }, { prompt: "Seleziona un piano formativo" }) %>

<div id="hiddenField" style="display: none">
    <div class="row">
        <div class="col-xs-12">
            <div style="margin: 20px 20px;">
                <%= link_to 'Genera report', generate_project_resource_associations_admin_projects_path, :class => "btn btn-default" %>
            </div>
            <div class="box">
                <!-- /.box-header -->
                <div class="box-body" id="table-box">
                    <%= render :partial => "table" %>
                </div>
                <!-- /.box-body -->
            </div>
        <!-- /.box -->
        </div>
    </div>
</div>

Upon selecting a project from the list, the partial /admin/projects/_table will be displayed using the script below:

$("#project_report").change(function(){
    if ($(this).val() !== '') {
        $("#hiddenField").show();
        var project_id = $(this).val();
        $.ajax({
            type: "GET",
            url: "/admin/projects/report_project_resources.js",
            data: {
                projectId: project_id
            }
        });
        console.log(data);
    }
    else if ($(this).val() === '') {
        $("#hiddenField").hide();
    }
});

I have created a /admin/projects/report_project_resources.js.erb file with:

$('#table-box').html("<%= escape_javascript (render partial: 'table') %>");

To load the partial content. In my current partial _table file, I am testing the passed params with:

<h1><%= params[:projectId] %></h1>

To troubleshoot why I can't access the project found by @project variable in the controller. In /admin/projects/projects_controller.rb:

  def report_project_resources
    @project = params[:projectId]
    project = Project.find_by(id: @project)
  end

If anyone could provide assistance or guidance, it would be greatly appreciated. Thank you.

Answer №1

Hey there, I'm still getting the hang of this, but could this possibly be useful to you?

config/routes.rb

get :report_project_resources, to: "projects#report_project_resources", as: :report_project_resources

report_project_resources.html.erb

<%= select_tag "project", options_from_collection_for_select(Project.all, "id", "name"), prompt: "Select something", id: "project-select" %>

<div class="box-body" id="table-box">
  <%= render partial: "shared/table", locals: { report: "" } %>
</div>

shared/_table.html.erb (partial)

<h1><%= report.present? ? report.name : "None" %></h1>

projects/projects_controller.rb

def report_project_resources
  @report = params[:projectId].present? ? Report.find_by(project_id: params[:projectId]) : ""
  respond_to do |format|
    format.html { render partial: "shared/table", locals: { report: @report } }
  end
end

app/assets/javascripts/projects.js

$('#project-select').on('change', function (){
   var project_id = $(this).val();
   $.ajax({
       type: "GET",
       url: "/report_project_resources",
       data: { projectId: project_id }
   }).done(function(result) {
      $("#table-box").html(result);
   }).fail(function() {
       console.log("error")
   });
 });

It might not be perfect for your needs, but here's hoping it gives you a hand! :)

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

Grabbing messages upon Page load utilizing Strophe js

I am currently working on retrieving messages whenever a User logs in and when the page loads. Currently, I am able to retrieve messages only when a User sends a message to another User using the onMessage function. Here is the code snippet: var archive ...

Struggling with inserting JavaScript into the <input type="date"> calendar

Objective: I am trying to automate a calendar on Chrome using Selenium (Python + behave). The problem: Despite attempting to pass a value via JavaScript, the date is only set when physically clicked through the calendar. Keyboard input and JS method do no ...

Error: $(...).DataTable function is not recognized - DataTables requires $.noConflict(true) to function properly

Recently I stumbled upon DataTables and decided to experiment with it. My goal for the page is to search and display posts based on user-defined parameters, updating the table content with JSON without having to refresh the entire page. However, I'm e ...

Anticipate the occurrence of an event in Node.js

Is there a way to wait for an event in node js? In my bpmn workflow development, I need to execute the events step by step. Each script represents an event within the server that consists of multiple scripts. For example: 'use strict'; const Bpm ...

Eliminate any parentheses and quotation marks from the string once it has been JSON.stringify'd

My goal is to transmit data to the API by passing an array to the ajax request. Initially, I used the JSON.stringify() method. var string = JSON.stringify(Allsubjects); //string = "["Mathmatics","English","Hindi","Science","Social Science"]" It should be ...

Encountering the error code [$injector:unpr] regarding an unknown provider: $uibModalInstanceProvider

In my web application, I have a controller called AddPrice. This controller is invoked from a Price listing screen as a popup using the $uibModal.open method, where the controller is passed in as an argument. However, the controller is not defined within t ...

What is causing my switch statement to not align with any cases?

Whenever I implement a switch statement, none of the cases seem to match the 'prefix' value. However, when I switch to using an if-else statement instead, everything functions correctly. What could be causing this discrepancy? Thanks in advance ...

Is there a way to transpile a dependency within the node_modules directory when using Nuxt 2?

I have come across challenges when transpiling node_modules with Nuxt, but the latest version of Nuxt (2.0) seems to have addressed this issue by introducing a transpile option in the nuxt.config.js file. https://nuxtjs.org/api/configuration-build/#transp ...

Docusign has encountered an issue: 'The envelope you are trying to access either does not exist or you do not have the necessary permissions'

As a newcomer to docusign, I encountered an error while trying to implement it and access the document list. API Call Result: { errorCode: 'ENVELOPE_DOES_NOT_EXIST', message: 'The envelope specified either does not exist or you have no ...

Exploring Rotation Challenges in Photogrammetry Reference Cameras within a Three-Dimensional Environment Using THREE.JS and Reality Capture

Greetings to everyone who has taken the time to read through my post. I am hopeful that not only will this post be beneficial for me, but also for others who may come across it! A Brief Overview Currently, my focus is on a project involving point clouds c ...

Issue with VueJs Rendering: Property or Method Undefined in V-for Render

I've encountered a strange bug that I can't seem to pinpoint the cause of. My issue revolves around implementing a v-for loop in my blade view, and I'm receiving this error message: "[Vue warn]: Property or method "question" is not defin ...

Updating databases with the click of a checkbox

Currently, I am developing a program for monitoring cars as part of my thesis. My current focus is on user management, and I have come across an issue where the database needs to be updated when the status of a checkbox changes. To visualize checkboxes, y ...

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

Dialog box for confirmation/Alert box for SweetAlert before sending Ajax POST request

One issue I am encountering is with an Ajax POST function that submits a form. In the beforeSend() function, there is a sweetAlert dialog that prompts the user to either abort or continue the Ajax POST call. The problem arises when the success function tri ...

Does the Loopback Model have an "exists" method that includes a where clause?

I am interested in querying the data using filters to check for existence. Does loopback support this method of querying? If so, could you provide some guidance? myModel.exists({where: {and: [{city: "London"}, {gender: "F"}]}}, function(err, bool){ if(bo ...

When checking the form action property in IE6, make sure to account for forms that have a field specifically named "action."

If I have the following form: <form id="myForm" action="index.php"> <input type="hidden" name="action" value="list" /> <input type="submit" /> </form> How do I retrieve the value of the action attribute of the form (index. ...

Retrieve information using server-side rendering

I'm faced with a situation where my page utilizes query parameters to fetch data via SSR. The challenge arises when these query parameters frequently change, triggering a re-fetch of the data using SSR despite there being no client-side data fetching ...

Unable to insert controller into routeprovider

Currently, I am working on an exercise in AngularJS to enhance my skills focusing on routes. However, I am facing issues with getting the controller attributes to function correctly inside the routed template. Despite reading numerous tutorials, the code s ...

Unable to load module/controller file from Angular 1 into view/html

var app = angular.module("appModule",[]); app.controller("viewController",function($scope){ $scope.greeting = "Welcome to the future"; }); <html> <head> <script src="Scripts/script.js"></script> <script ...

Encountered a problem when attempting to access an element on a PHP page using

My javascript code is supposed to retrieve information from a specific URL (song.php) which contains the name of a song. However, there seems to be an issue as the javascript is not extracting the required data. Below is the HTML element and javascript fo ...