1

Every Ingredient has one Category.

First a user selects a Category then

store all ingredients of that category into a second select field.

<%= select("category", "category_id", Category.all.collect {|c| [ c.name, c.id ] }) %>

My approach is to update the second select field with ajax, but once placing the ajax call after the alert statement the whole function is not called anymore.

$(document).ready(function(){
  $(document).on('change', '#category_category_id', function(){
    alert("changed");
    $.ajax({
      url: "categories/category_selection",
      type: "GET",
      data: {'ingredient=' + $('#ingredient_selection option:selected').value() },
    })
  });
});

Same with

$('#category_category_id').live('change', function(){...})

Categories_controller.rb

class CategoriesController < ApplicationController
  def category_selection
    respond_to do |format|
       format.js {  }
    end
  end
end

Category_selection.js.erb

$('#category_category_id').after('
  <%= select_tag :category_selection, 
    options_from_collection_for_select(@ingredients, :id, :name), 
        :prompt => "Ingredient" %>
');
3
  • So the function works without the ajax call? I would remove the last comma in the ajax call (after the data hash). I would also add a semi-colon after $('#ingredient_selection option:selected').value() Commented Jul 18, 2015 at 19:31
  • $.ajax({ url: "categories/category_selection", type: "GET", data: {'ingredient=' + $('#ingredient_selection option:selected').value(); }}) doesnt work (also with an semicolon at the end) Commented Jul 18, 2015 at 19:44
  • Hmmm. What errors are you getting in your browser's console when you run that? Commented Jul 18, 2015 at 19:46

1 Answer 1

1
{'ingredient=' + $('#ingredient_selection option:selected').value() }

Causes a syntax error. The brackets are interpreted as the beginning of an object literal but instead you have an expression which evaluates into a string.

You should pass a string or object as the data parameter.

data: 'ingredient=' + $('#ingredient_selection option:selected').value(),

or an object:

data: { ingredient: $('#ingredient_selection option:selected').value() },

I would recommend that you learn to use the browser console.

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Now the alert is executed. But the view stays untouched
You do realize how ajax works? It does not replace the page content.
If you look in the network tab you can see the request, but if you actually want to do something with the data you needto register a success handler. Google for "jquery ajax tutorial"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.