Troubleshooting: Issue with Passing Variable from Controller to Partial in Rails with AJAX

I am facing an issue with passing a variable from my controller to a partial asynchronously. My goal is to render a form on my view after the user selects an option from a drop-down menu. However, I keep encountering the following error:

undefined local variable or method `shipment_options' for #<#    <Class:0x007f92941be8f0>:0x007f929ca78ad8> 

This error persists even when I use something like locals: { var: @var }. Below is the code snippet from my view:

<body>
  <p>
    This is body<br>

    <%= select_tag :service, options_for_select(usps_services), { id: "service_select", remote: true } %><br>

  <div id='shipment_option'>
    <%= render 'shipment_option', remote: true, locals: { shipments: @shipment_options } %>

  </div>
</body>
<script>
$('#service_select').on('change', function () {
    var service = $('#service_select').val();
    $.ajax({
      type: "POST",
      url: '/service_select',
      format: 'js',
      data: { service: service, order_id: <%= params[:order_id] %> },
      success: function (data) {
        console.log(data.rates);
        return true;
      },
      error: function (data) {
        return false;
    }});

});
</script>

The route that handles the AJAX request

#AJAX
post '/service_select' => 'dashboards#get_shipment'

The get_shipment method in the controller

def get_shipment
  order = Order.find(params[:order_id])
  respond_to do |format|

  from_address = EasyPost::Address.create(
    :street1 => Rails.configuration.from_address[:street1],
    :street2 => Rails.configuration.from_address[:street2],
    :city => Rails.configuration.from_address[:city],
    :state => Rails.configuration.from_address[:state],
    :zip => Rails.configuration.from_address[:zip]
  )

  to_address = EasyPost::Address.create(
    :name => order.name,
    :street1 => order.street1,
    :street2 => order.street2,
    :city => order.city,
    :state => order.state,
    :zip => order.zip
  )

  parcel = EasyPost::Parcel.create(
    :predefined_package => params[:service],
    :weight => 10
  )

  @shipment_options = EasyPost::Shipment.create(
    :to_address => to_address,
    :from_address => from_address,
    :parcel => parcel
  )
  format.js { render json: @shipment_options, action: "new" }
end 

And here's the code in the partial I intend to render

<%= form_for(@shipment) do |f| %>
  <% shipment_options.rates.each do |rate| %>
    <%= f.label :shipment_service %> 
    <%= rate.service + " " + rate.rate.to_s %>
    <%= f.check_box :shipment_service %>
  <% end %>
  <%= f.submit "Ship package" %>
<% end %>

Please advise on how to resolve this error. Thank you.

Answer №1

There seems to be a discrepancy - you've passed @shipment_options as shipments in your partial, but the actual method being called in your partial is shipment_options, which has not been defined.

Answer №2

After troubleshooting, I successfully resolved the issue by removing all arguments from format.js in my controller and renaming the file .js.erb to get_shipment.js.erb. This allowed me to properly set the @shipment_options variable before rendering the partial with the following code:

$('#shipment_option').html("<%= j(render 'shipment_option') %>");

As a result of setting the instance variable correctly, the form rendered as expected.

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

Generate an array in JavaScript using the values from input fields

Is there a way to create a JavaScript array that stores the values of all input fields with the class 'agency_field', when there are x number of these fields in the form? I attempted to achieve this using jQuery, but encountered a syntax error. ...

Rails capybara found multiple ambiguous matches, resulting in 50 elements matching the CSS

I encountered the following error: There seems to be a conflict, as 50 elements were found with matching css "input[value=\"delete\"]" This error occured when executing the following code snippet: find('input[value="delete"]').first. ...

Is there a way to convert a URL into a user-friendly json format displayed on a web page

Can someone please help me figure out the proper way to convert this URL into a JSON format that is easily readable using jQuery on an HTML page? ...

Please indicate the decimal separator for the Number() function

UPDATE : TITLE IS MISLEADING as testing showed that Number() returned a dot-separated number and the HTML <input type="number"/> displayed it as a comma due to locale settings. I changed to using an <input type="text"/> and filtered keydown lik ...

Wrap the json response in HTML elements

I'm currently learning about AJAX, and I've encountered a major issue that I can't seem to resolve. I pass several variables to PHP, perform various checks there, and then return string values to AJAX. Strangely, I am able to display these r ...

php utilizing javascript to generate encrypted data for a hidden file

Within my MVC application, I have implemented Raty for rating images. Below is the code snippet: <div class="container"> <form method="post" class='form' role='form' action="?section=photo&view=addVote"> <input t ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Managing and keeping track of a universal value within the success callback function among numerous Ajax POST requests

I am faced with a challenge involving two HTML elements: 1). a div element that functions as a multiple select, created automatically by a predefined widget, and 2). a button that triggers an onclick event. On the JavaScript side, I have a global variable ...

Ajax issue: unable to retrieve $_SESSION data. Works on local environment but not on web server

I've been working on a website project that involves using jQuery to interact with a database. I store the user ID in a session for updating and deleting purposes. Everything seems to be running smoothly on my localhost (Wamp server), but when I uplo ...

Is there a correct way to accomplish this task? How could I go about achieving it?

Currently, I am delving into the world of react. While following along with some video tutorials, I encountered a roadblock in the request.js file. The issue popped up during the build process ./src/Row.js Line 16:45: 'fetchUrl' is not define ...

Implementing fullCalendar's addEventSource function with the color customization feature

One feature of my application involves dynamically adding events to the calendar. function AddEventSourceDetailed(act_id) { $('#calendar').fullCalendar('addEventSource', function (start, end, callback) { var startTime = Mat ...

Unable to access $_SESSION variable when making AJAX request from a different port

After creating a website with PHP on port 80 (index.php) and setting the session variable with the userid upon login, I encountered an issue when clicking on a link that redirected me to port 8080, which is where a JavaScript file containing node.js proces ...

center text above images in flexbox when page is resized

When resizing the page, I'm facing an issue where the links overlap with the images in a flexbox layout. It seems like the padding and margin between the images and links are not working due to them not being "related" or connected. I believe I need t ...

Designating a class for the main block

Having an issue with a slider in uikit. When the slide changes, the visible elements also change their class to uk-active. I'm trying to select the central element from the active ones but css nth-child doesn't work. Any suggestions on how to do ...

Is there a way to extract the visible text from an HTML TextNode without including the HTML tags?

My current challenge involves converting a DOM node and all of its children into plain text markup of a custom design. Utilizing node.childNodes allows me to retrieve a list of all content, which can then be recursively transformed into my desired string f ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

Form in Rails featuring both ajax and non-ajax buttons

My @object form has two buttons: one for rendering the 'show action' and the other to refresh the same form using ajax. I'm wondering if it's possible to have both a non-ajax button and an ajax button in the same form, or if I need to ...

Tips on Including Static Header and Footer in Multiple HTML Pages

What is the best way to reuse a header and footer on multiple HTML pages without repeating code? I have 5 HTML pages that all need to include the same header and footer elements. How can I efficiently reuse these components across all pages? ...

Passing and removing array parameters in HTTP requests using Angular

I have an Array of statuses objects. Each status has a name and a boolean set to false by default. These represent checkboxes in a form with filters - when a checkbox is checked, the boolean value is set to true: const filters.statuses = [ { name ...