Optimal location for executing Js to render a partial within the Rails framework

I had a plan to update a partial using a click event where data was fetched via ajax. I navigated to my assets/javascripts directory and placed the code in the js file of the module I intended to call it on. I successfully fetched the data and performed some "html() or text()" operations on the div. However, when I tried to execute

.html("<%= escape_javascript( render( :partial => 'job') ) %>")

my controller returned an error stating that the method "render" was unknown. After reading several other discussions, I learned that the assets directory was not meant for static content. This led me to the question: where should I place it if not in assets? I attempted to put it in the view/model folder (with the same name as the action 'show'), but it failed to load. Yes, I informed the Controller in the show action to respond_to format.js.

So, where should I locate the js File and how should I invoke it? Or is there a way to keep it in the assets directory and still be able to call render?


Thank you for your response! Unfortunately, despite following your instructions, it still doesn't work. Here's my Code:

/app/views/events/show.js.erb.coffee:

$(document).ready ->
  url = window.location
  url = String(url).split('/')
  event_id = url[$.inArray( "events" , url) + 1]
  $('.position').click ->
    position_id = $(this).attr("id")
    $.ajax '/events/'+event_id+'/eventpositions/'+position_id+'/eventjobs'
      dataType: 'json'
      success: (result)->
        $( '#'+position_id ).find('.jobs').html("<%= escape_javascript( render( :partial => 'job') ) %>")
        alert result[1].job_id

/app/views/events/show.html.haml:

%p#notice{:xmlns => "http://www.w3.org/1999/html"}= notice
%p
  %b Name:
  = @event.name
  \ 
  %b Plz:
  = @event.plz
%p
  %b Personal:
  - @eventpositions.each do |p|
    .position{:id => "#{p.id}"}
    %b
      Position: #{Position.find(p.position_id).name} Anzahl: #{p.quantity} Aufträge: #{p.eventjobs.all.count}
    .jobs

  = link_to 'Neuer Auftrag', new_event_eventposition_eventjob_path(@event.id,p.id)
  %br
  %br
= link_to 'Neue Position', new_event_eventposition_path(@event.id)
= link_to 'Edit', edit_event_path(@event)
|
\#{link_to 'Back', events_path}

/app/views/events/_job.html.haml:

.jobs
  - eventjobs.each do |j|
    User: #{User.find(Job.find(j.job_id).user_id).email}
    %br

/app/controllers/events_controller.rb:

def show
  @agency = Agency.find(current_agent.agency_id)
  @event = @agency.events.find(params[:id])
  @eventpositions = @event.eventpositions.all

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @event }
    format.js
  end
end

The code works without JavaScript. Everything renders correctly. However, my main issue now is that it doesn't respond to a click event when placed in the app/views/events Folder. If I move it to the assets directory, it works perfectly fine but doesn't render. What am I missing here? Why isn't my js Code being loaded?

Appreciate your assistance!

Answer №1

Typically when dealing with this type of scenario, I like to give it a name related to its specific function, such as display.js.erb, and then utilize the format.js in the controller just like you did. If you're using coffeescript, remember to name it display.js.coffee.erb. If this approach doesn't solve the issue, could you please share the code snippet from your view where the onclick event is being set up?

Edit based on utilizing the display javascript code

Considering you are utilizing the show action, you can simply achieve this:

= link_to "Show", @event, :remote => true, :format => :js

You may adjust the event variable according to your requirements, but it should get the job done

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

Combining the powers of Express.js, Sequelize, and advanced form validation

As a beginner with Express and Sequelize, I am looking to utilize Sequelize's validation functionality for form submissions without having to duplicate validations on the frontend or rely on additional libraries like express-validator. Below is an exa ...

Is it possible to develop a chat application utilizing asynchronous processing in Tomcat 7?

Can a chat application be created using the Servlet 3.0 specification and implemented in Tomcat 7 without needing an additional reverse-ajax library? What is the purpose of asynchronous processing? ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

How to specifically exclude a checkbox from the "select all" function in J

One way to select all checkboxes with HTML code: Select All <input type="checkbox" name='select_all' id='select_all' value='1'/> To achieve this with Javascript code: <script type="text/javascript> $(&apos ...

Retrieving information from deeply nested JSON structures within React components

I am developing a web application that focuses on searching and displaying movie information. One of my challenges is accessing nested objects like "principals" from the same endpoint that contains the main object "title". Upon fetching the JSON response: ...

The ng-grid selectRow function becomes undefined when the rowTemplate is being set

Setting the rowTemplate on the ngGrid options causes all rows selection functions, like selectRow, to become undefined. This issue is quite perplexing. For a demonstration, check out this link: http://plnkr.co/edit/m4GZftllwZzjYkEvXo3u?p=preview // main. ...

Is there a restriction on the amount of data that can be

I have provided the code snippet below for reference: <System.Web.Services.WebMethod()> _ Public Shared Function LinkedUSNs(ByVal usn As String, ByVal requester As String, ByVal reason As String, ByVal terminalip As String, ByVal strCon As Strin ...

What is the best way to automatically redirect to a different page once a video has finished playing after 10 seconds?

I'm working on creating an HTML page that will automatically redirect after 10 seconds once a video has finished playing. The issue I'm facing is that the page is currently redirecting as soon as it loads, rather than waiting for the video to fin ...

Alter the style attribute using JavaScript

I have a calendar table row that needs to be displayed or hidden based on the month. HTML: <tr id="bottomrow" class="week" valign="top" style="display:none;"> <td class="day" id="d36"> <div class="daynumb" id="x36">& ...

What is the best way to refresh the datatables upon clicking a button?

I have a button labeled "add data". When this button is clicked, the datatables increase in data. However, they do not automatically reload and require manual reloading. How can I make it so that when the "add data" button is clicked, the datatables automa ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

Uploading videos to YouTube via Ajax

I've been working on implementing resumable video upload functionality for Youtube by following the instructions provided in the Youtube Resumable Upload API. However, I encountered an error message: "NetworkError: 404 Not Found - ". Below is the ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

"Encountering a new error with the creation of a user using AngularJS and Firebase

Attempting to create a user using Angular. myApp.controller('loginCtrl',['$scope','$firebaseAuth','config',function($scope,$firebaseAuth,config){ console.info('[APP-INFO] ~ loginCtrl Start') var ref = ne ...

Having issues with jQuery Checkbox Selector and .attr('checked) function not functioning correctly?

I'm trying to assign the value of a variable as true or false based on the selected checkbox. However, the code I have is not working as expected. <input type="checkbox" id="chkBox1"> var chkBox1Val = $('#chkBox1').prop('checked ...

What is the method for a JavaScript program to determine if a global property name has been defined according to the ECMA-262 standard

Imagine creating a function called checkIfEcmaGlobal which would return true for recognized names of ECMA-262 globals. $ node > checkIfEcmaGlobal('Array') true > checkIfEcmaGlobal('process') false What approach could be taken to ...

Slice or eliminate the PlaneGeometry using XY coordinates

Just starting out in learning Three.js and looking to achieve the following: const customPlaneGeometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); if(customPlaneGeometry.x > 2 && customPlaneGeometr ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Restricting the drop zone for a jqueryui sortable element

In my HTML code, I have a list of elements inside a ul tag. The last li element is supposed to create new items. I used jqueryui's sortable() function to make the ul sortable, but excluded the last li element from being draggable. However, other items ...

Node.js provides a simple way to display basic alerts

Within my form, users are prompted to input their email, password, and class. To serve the HTML file from node.js, I utilize the following code: app.get('/', function (req, res) { res.sendFile(path.join(__dirname + '/Login-Signup.html&a ...