Eric Baldwin Eric Baldwin - 5 months ago 21
jQuery Question

Making a POST request using jQuery's Ajax and Rails

I want to load a set of objects and render them using Ajax and a

select
element in HTML. Here is the jQuery I use to make the request:

planner.js

$("select.semesterSelect").change(function(){
$.ajax({
type: "POST",
url: "/planners/events",
data: {timeperiod: {id: $(this).find(":selected").val()}},
success: function(events){
console.log("success");
},
error: function(){
console.log("error");
}
});
});


Here is the controller action I'm using to find the objects I want to render:

planners_controller.rb

def events
@timeperiod = params[:timeperiod] ? Timeperiod.find(params[:timeperiod][:id]) : Timeperiod.find(Timeperiod.last.id)
@events = Event.where("from_date >= :tp_from_date AND to_date <= :tp_to_date", {tp_from_date: @timeperiod.from_date, tp_to_date: @timeperiod.to_date})
respond_to do |format|
format.html
format.js
end
end


Finally, here is the js.erb file I'm using to render the events (I've commented out the rendering line).

events.js.erb

//$("#events_div").html("<%= escape_javascript(render(:partial => 'planners/event')) %>");
console.log("here");


When I make a selection using this setup, I get "success" in the js console log. However, I do not see "here". When I uncomment out the rendering line, I it doesn't render my new objects.

What am I doing wrong?

Edit: I corrected the filenames.
Edit 2: Below are links I used to format this code.

"Working with JavaScript in Rails": http://guides.rubyonrails.org/working_with_javascript_in_rails.html
"how to do render partial on jquery ajax success method with rails 3": how to do render partial on jquery ajax success method with rails 3

Answer

I solved the problem by splitting the planners/events action into two events as follows:

  def events
   @timeperiod = params[:timeperiod] ? Timeperiod.find(params[:timeperiod][:id]) : Timeperiod.find(Timeperiod.last.id)
   @events = Event.where("from_date >= :tp_from_date AND to_date <= :tp_to_date", {tp_from_date: @timeperiod.from_date, tp_to_date: @timeperiod.to_date})
    respond_to do |format|
      format.html
    end
  end

  def events2
   @timeperiod = params[:timeperiod] ? Timeperiod.find(params[:timeperiod][:id]) : Timeperiod.find(Timeperiod.last.id)
   @events = Event.where("from_date >= :tp_from_date AND to_date <= :tp_to_date", {tp_from_date: @timeperiod.from_date, tp_to_date: @timeperiod.to_date})
    respond_to do |format|
      format.js
    end
  end

As you can see, events2 renders jQuery and events renders html. I also modified my js function to use the second function.

planner.js

$.ajax({
    type: "POST",
    url: "/planners/events2".
...

This executes code in events2.js.erb. This is unwieldily. Does anyone have a solution that doesn't involve splitting into two different actions like this? I'd be happy to accept a better solution.