Using Rails to render a partial containing a form object

I need help with rendering a partial called 'colordata' after selecting a color from a dropdown list using Ajax. Unfortunately, I'm not seeing any changes on the main page and the form is undefined in the colordata partial.

This is the schema of my Order model:

create_table "orders", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string "design"
    t.integer "quantity"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "color"
    t.string "lotnumber"
    t.float "consumption", limit: 24
    t.string "number"
  end

Here's the Ajax call:

$("select[name='order[color]']").change(function(){
     $.ajax({
       url: "colordata",
       type: "post",
       data:{
         "color": $(this).val()
       },
       dataType: JSON,
       success: function(data){
       }
     });
   });

This is the controller:

def colordata
    request.POST.each do |key, value|
      @color = value
    end
    @lotdetail= Master::Yarn.where('color like?', @color)
    respond_to do |format|
      format.js
    end
  end

The Colordata.js.erb file:

$(".lot").innerHTML += "<%= escape_javascript(render(partial: 'colordata'),locals: {form: form) %>"

The partial _colordata.html.erb:

<%= form.label :lotnumber %>
<%= form.collection_select(:lotnumber, @lotdetail, @lotdetail.lotnumber,@lotdetail.lotnumber,prompt: "Select the Yarn")%>

The errors encountered are:

  1. Form is not defined in _colordata.html.erb
  2. The partial is not appending into the class lot.

Thank you for your assistance.

Answer №1

If you want to include your partial using jquery, try using the append method instead. Make sure to define your locals within the render function. Here's how you can do it:

$(".lot").append("<%= escape_javascript(render(partial: 'colordata', locals: { form: form })) %>")

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

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

Node.js equivalent of hash_hmac

I am facing an issue while trying to sign the URL in a Node.js application similar to how it is done in my PHP app. In PHP, I use the following code to sign the URL: private static function __getHash($string) { return hash_hmac('sha1', $stri ...

I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // ...

What is the best method for directing a search URL with an embedded query string?

Currently, I am developing an express application that has two different GET URLs. The first URL retrieves all resources from the database but is protected by authentication and requires admin access. The second URL fetches resources based on a search para ...

What techniques can I use to generate a 3D visual effect by shifting the background image layer as the user scrolls (creating a Parallax effect

I have combined two images in the heading; one on top of the other. My goal is to create a subtle vertical movement in the background image as the user scrolls, giving the illusion of depth. Both images share the same width, but the background image is tal ...

Is it possible to include a value for the "src" attribute rather than the "class" attribute in the array of values in list.js?

Check out the HTML code I wrote: <html> <head> </head> <body> <input class="search" placeholder="Search" /> <div id="users"> <ul class="list"> ...

Guide on incorporating the ":gt" filter from sizzle into vanilla javascript

I am currently working on adapting a jQuery plugin to be compatible with the AngularJS JQlite API, but I have encountered some challenges along the way. Here is an overview of the plugin: (function (e) { var $product = $('#product'), ...

Simple chart with four sections in DimpleJS (D3)

Recently I decided to give DimpleJS a try for the first time with hopes of creating something like this: However, I seem to have run into some trouble. No matter what I do, nothing appears on the screen. http://jsbin.com/xosehedejo/1/edit window.onloa ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

Stop a user from adding duplicate tasks

I have developed a JavaScript code for creating a todo list. Currently, I am working on the phase of adding tasks to the list. The user wants to ensure that if a task is entered once, it cannot be entered again. const taskInput = document.getElementById(&a ...

Tips for retrieving information from an action method with AJAX in asp.net core

My goal is to retrieve all the tickets from an action method and return them as JSON to display in the view. The code I have written only shows the JSON without populating the table. I need to fetch the data and show it in a tabular format. Here is the out ...

Customize the text displayed in a dropdown menu in Angular Material based on the selection made

I am working with a multi-select dropdown menu that includes an option labeled "ALL" which, when selected, chooses all available options in the list. My goal is to display "ALL" in the view when this option is chosen or when the user manually selects all t ...

Template does not reflect changes made to filters in real-time

I've been working on filtering my "PriceList" collection and sorting is functioning perfectly. However, I'm experiencing some issues with implementing filters and search functionality. When I click on custom filter buttons, the template doesn&apo ...

Can an AJAX request continue running even after the user has moved to a different page within the website?

Currently on my website, users are able to submit a form using ajax. The response, indicating whether the form was successfully submitted or if there was an issue, is displayed in an alert message. However, due to the asynchronous nature of this process, i ...

Tips for changing the first letter to uppercase in a p5.js variable

I'm currently working on developing a weather forecasting website using the p5.js framework in JavaScript. One issue I am facing is that the API I am utilizing only provides weather descriptions in lowercase format, whereas I want them to be displayed ...

React transmits an incorrect argument through the function

Having a bit of trouble passing a parameter alongside the function in my for loop to create SVG paths. The props are working fine with the correct 'i' value except for selectRegion(i) which ends up getting the final value of 'i' after t ...

How can I use jQuery UI to slide a div, while also smoothly moving the adjacent div to take its place?

Wishing you an amazing New Year! I am looking to create a smooth sliding effect for a div when a button is clicked. I want the adjacent div to slide alongside it seamlessly, without any clunky motions or delays. Currently, the adjacent div only moves afte ...

Enhance your AngularJS skills by incorporating multiple conditions into the ternary operations of ng-class

I am struggling to apply multiple classes when the condition in the ng-class attribute evaluates to true. Here is the code I have attempted so far, but it doesn't seem to be working: <div class="col-md-4" ng-mouseover="hoverButton=true" id="plai ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

Transferring data between View and Controller in MVC version 2

I'm often puzzled by the best method for passing values between Views and Controllers in MVC. While I understand that I can set ViewData in the Controller and access it in the View, I struggle with how to pass values back from the View to the Controll ...