javascript - Pass select value to controller without refreshing the page (AJAX, RAILS, JS) -
i'm newbie using ajax , i'm trying work on group of select boxes when user selects value first, second updates values. i'm trying use ajax, jquery , ror, far, can't fetch value first box , pass controller in order filter results of second.
this code index.html.erb
<%= form_tag(posts_path, remote: true, :method => 'get', class: "forma") %> <%= select_tag("box", options_from_collection_for_select(@posts, :content, :content), :prompt => "select") %> <p> <%= select_tag("nbox", options_from_collection_for_select(@listposts, :content, :id), :prompt => "select") %> <p> <%= submit_tag "show", class: "btn btn-info" %> <% end %>
this index.js.erb
$(document).ready(function() { $(".btn").on("click", function() { $('.table').fadetoggle(); }) $('#box').change(function(){ $.ajax({ type: 'post', url: '/jess/rails/dummy/app/controllers/posts_controller', data: {'filter' : $(this).val() }, success: function(data){ } }) $('#nbox').fadein(); $('.btn').fadein(); }) })
this controller
class postscontroller < applicationcontroller respond_to :html, :js def new @post = post.new end def create @posts = post.all @post = post.new(post_params) if @post.save flash.now[:notice] = "yeah" respond_to |format| format.html {redirect_to @post.content} format.js end else render "/" end end def show @post = post.find(params[:id]) end def index @posts = post.all @listposts = post.where('content ?', params[:box]) end def next @listposts = post.where('content ?', params[:box]) end private def post_params params.fetch(:post, {}).permit(:content) end end
i think i'm doing wrong ajax part in js.erb i've changed many times don't know anymore. appreciated!!
it looks there couple of small problems.
first, looks url using may wrong. url ajax request same format url if view page in browser.
with provided can't tell should be, can give example. assuming access index page "http://example.com/index" (or similar), call function want based on it's route. if route "update", "http://example.com/update".
basically, don't use folder path use web path instead.
second, don't success callback in ajax request. ajax, send , receive info server, have use javascript update whatever need updated manually. so, you'll need have update action return information can use change state of second set of boxes.
Comments
Post a Comment