How to make AJAX responses work from the Rails side?

半城伤御伤魂 提交于 2019-12-03 20:38:10

This looks exactly like a question that I just answered today for another user... same model names and everything.

def create
  @subscriber = Subscriber.new(#your params)
  respond_to do |format|
    if @subscriber.save
      format.js { render :json => @subscriber, :status => :created, :location => @susbscriber }
    else
      format.js { render :json => @susbcriber.errors, :status => :unprocessable_entity }
    end
  end
end

Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.

In the .erb file that contains the form, you would add the following javascript:

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#your-form")
    .bind("ajax:loading",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(event, data, status, xhr) {
      $("#response").html(data);
    });
    .bind("ajax:failure", function(event, data, status, xhr) {
      //your code
    });
});

A standard respond_to block (this allows both html and js) would be:

respond_to do |format|  
  if @subscriber.save  
    format.html { redirect_to(@subscriber, :notice => 'Subscriber created.') }  
    format.js # Not redirecting, just spitting out the JSON(js?) response (I believe).  
  else  
    format.html { render :action => "new" }  
    format.js # Not redirecting for js and this time return error response. 
  end  
end  

So what you have actually looks ok to me. Is it working ok or is there an issue?

The above should work with rails2 and rails3. Rails3 has a more succint syntax (of course) but given you are Rails2 I'll leave that for now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!