How can Ajax assist in utilizing a JavaScript variable within a Rails call that is made within a JavaScript function?

I'm facing a challenge where I need to update a Ruby on Rails partial within a view using a JavaScript object-defined variable, but I'm struggling to make it work. Despite my research pointing towards using an Ajax call as the only viable solution, I'm having trouble understanding why this is necessary (considering the JavaScript variable is already available before the Rails command) and how exactly to go about implementing it.

Within my Rails view, there is a section of HTML code that I aim to modify:

<div id="myevent">
    <% if @pocket.events.any? %>
        <%= @event = @pocket.events.first %>
        <%= render @event %>
    <% end %>
</div>

In the same view, I've integrated a JavaScript object consisting of clickable nodes, each representing a unique event with an individual identifier. My objective is to refresh the #myevent section above whenever a user clicks on a different node.

Being new to front-end development, I've attempted the following approach:

timeline.on('click', function (properties) {
    logEvent('click', properties);
    var item = properties["item"];
    $('#myevent').html("<%= escape_javascript render (@pocket.events.find_by id:" + item + ") %>");

The JavaScript variable 'item' contains the event id from the clicked node. However, the last line in the snippet above results in an ArgumentError being raised by Rails with the message:

'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.

To my surprise, the code does function properly when I hardcode an id, indicating that the logic behind my approach is correct:

$('#myevent').html("<%= escape_javascript render (@pocket.events.find_by id: 5) %>");

I also experimented with utilizing a partial format:

$('#event').html("<%= escape_javascript render :partial=>'shared/event', :locals=> {event_id: " + item + "} %>")

And then tried fetching the appropriate event in the 'shared/event' partial using the method below:

<%= @event = Event.find(event_id) %>

Unfortunately, this resulted in an ActiveRecord::RecordNotFound error as it failed to replace the string "+ item +" with the value of the JavaScript variable:

Couldn't find Event with 'id'=+item+

The main issue persists – I am unable to successfully incorporate the JavaScript-defined variable into these Rails calls. It seems like resorting to an Ajax call is the most feasible solution, but despite numerous attempts, I haven't been able to resolve this independently. Any assistance would be greatly appreciated.

Answer №1

It seems that the .erb code is only processed at render time, causing issues when trying to append to an undefined item. Hardcoding resolves this by enabling the ruby code to be parsed and rendered correctly.

Therefore, reaching out to the server is necessary.

To address this, you can try:

timeline.on('click', function (properties) {
    var item = properties["item"];
    $.ajax({
      type: "POST",
      url: '/route_to_your_controller',
      data: { event_id: item },
      dataType: 'json',
      success: function(data) {
        if (data['success']) {
          $('#myevent').html(data['html']);
        }
        else {
          alert('Oops, please handle this');
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log(errorThrown);
      }
    });
});

routes.rb

post '/route_to_your_controller', to: 'controller#spew_html'

If you have a corresponding route in your controller:

def spew_html
  # Handle failed finds, potential errors, check legality of ajax call, ensure request.xhr?, etc.
  event_id = params[:event_id]
  html_partial = render_to_string 'shared/event', locals: { event_id: event_id }
  respond_to do |format|
    format.json { render json: { html: html_partial, success: true } }
  end
end

Additionally, I recommend using the same route for both GET and POST requests whenever possible to simplify communication with the controller:

$.ajax({
  type: "POST",
  url: window.location.pathname,
  //...
});

This way, the controller will know how to handle it accordingly.

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

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

"Trying to execute this task without the required data leads to a 'The data needed to perform this action is currently unavailable' error message in IE7

I've come across various mentions of this issue online, but no definitive solution. My current problem involves making an asynchronous ajax call using jQuery's $.ajax() function. Within the error method of the ajax function, I have implemented co ...

Assistance required for JavaScript with Image and Hyperlinks

In the provided code snippet, I have included a javascript onclick function to the image tag. After clicking the image and then going back, the page remains on the current page rather than returning to the original page. Is there a way to prevent this beha ...

retrieve a string from a given array

I need to retrieve a string from an array in vue and display it on the screen. Here is the method I created for this purpose: displayFixturesName() { const result = this.selectedFixture.toString(); document.getElementById(& ...

Unable to execute script tag on PHP page loading

When I make an AJAX request to fetch JavaScript wrapped in <script> tags that needs to be inserted on the current page, how can I ensure that the code executes upon insertion? Here's the snippet I'm using to add the code: function display ...

The base64 conversion for the image is overflowing from the upload image field in react-draft-wysiwyg

I have a functional react-draft-wysiwyg editor application that allows me to add images. However, I am currently encountering an issue which is detailed below: https://i.stack.imgur.com/HTjAc.png This is the code snippet of what I have attempted so far. ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

JavaScript code encounters an error stating "TypeError: n is undefined"

I recently crafted a JavaScript script to accomplish a specific task, and overall it was working smoothly. However, as I attempted to simplify the code for a demonstration here on this platform, I encountered two issues. Unfortunately, during this 're ...

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

Can you explain the significance of the order of elements in the Three.js BufferGeometry vertex positions array?

This array showcases the vertex positions sourced from this particular section of the three.js official documentation: var vertexPositions = [ [-1.0, -1.0, 1.0], [1.0, -1.0, 1.0], [1.0, 1.0, 1.0],     [1.0, 1.0, 1.0],     [-1.0, 1.0, 1.0] ...

"How to dynamically fill a text input field from a table using jQuery when a specific value is selected, potentially involving multiple rows (possibly

Scenario I created a form that allows users to place orders for articles. These articles are displayed in a table within another form, where each article is listed with its code, description, and price. The goal is for users to select an article from th ...

How can I tally the frequency of characters in a given string using Javascript and output them as numerical values?

I am in the process of tallying the frequency of each individual character within a given string and representing them as numbers. For example, let's consider the string "HelloWorld". HELLOWORLD There is one H - so 1 should be displayed with H remov ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Attempting to streamline this function in order to avoid running it nine separate times

I have created a day scheduler and successfully saved data in local storage for one hour field. However, I am looking for a way to streamline this function so that I can use it across all 8-hour fields without duplicating the code. Can someone provide me w ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

The ng-disable function is not displaying correctly

var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.firstName = false; $scope.toggle = function(){ $scope.firstName = !$scope.firstName; }; }); <!DOCTYPE html> <html> & ...

Experiencing difficulties posting on route due to receiving an undefined object instead of the expected callback in Node Js

I am working on implementing a feature in my application where users can create a favorite route. When a user adds a campground to their favorites, the ID of the campground is saved in an array within the schema. The process involves checking if the campgr ...

Unlock the power of nested dynamic content creation with JavaScript

Every time I attempt to use getelementbyid on a dynamically loaded div, I receive null as the result. This occurs even after trying both window.onload = function () { and $(window).load(function() { index.html: <main > <div id="main-div"> ...

Unable to hear sound properly through Web Audio

I'm experimenting with playing a wav file using the AudioContext. I've noticed that it plays correctly when loaded with the <audio> tag (as demonstrated in this example on jsFiddle), but encounters issues when using AudioContext. var startB ...

Angular 6: TypeError - The function you are trying to use is not recognized as a valid function, even though it should be

I'm currently facing a puzzling issue where I'm encountering the ERROR TypeError: "_this.device.addKeysToObj is not a function". Despite having implemented the function, I can't figure out why it's not functioning properly or callable. ...