1

I want to render a partial 'colordata' after selecting a :color from the drop down list as it involves Ajax. I am not able to observe any change in main page. Even form is undefined in colordata partial.

Here's my schema of model Order

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){
       }
     });
   });

Here's 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

Here's the Colordata.js.erb

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

Here's the partial _colordata.html.erb

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

errors are

  1. form is not define in _colordata.html.erb
  2. Partial is not appending into the class lot.

Thanks in advance.

31piy
  • 23,323
  • 6
  • 47
  • 67
Amitoj Singh
  • 121
  • 1
  • 1
  • 7

1 Answers1

1

To append your partial with jquery, you can use the append method instead. locals should be define inside the render. So you can fix like that :

$(".lot").append("<%= escape_javascript(render(partial: 'colordata', locals: { form: form })) %>")
Sovalina
  • 5,410
  • 4
  • 22
  • 39
  • I am getting this error ActionView::Template::Error (undefined local variable or method `form' for #<#:0x00007ff194ea0e10> Did you mean? fork): $(document).on('turbolinks:load', function() { $(".lot").append("<%= escape_javascript(render(partial: 'colordata',locals: {form: form})) %>") )}; – Amitoj Singh May 06 '18 at 10:06
  • @AmitojSingh It's because the `form` variable is define nowhere inside your js.erb file (that i was assuming it was). You can find a solution [here](https://stackoverflow.com/a/11693756/9541423) for this issue – Sovalina May 06 '18 at 10:22
  • It works using fields_for tag in partial But append is still not working. – Amitoj Singh May 06 '18 at 10:41