The HTML form:
<form id="newsletter" method="post" action="/subscribers" data-remote="true">
<label for="email">Enter your email:</label>
<input type="text" name="email" class="text" />
<p class="btn"><span>Signup</span></p>
</form>
Note the data-remote="true"
The Controller:
class SubscribersController < ApplicationController
def create
@subscriber = Subscriber.create(:email => params[:email],
:ip_address => request.remote_ip )
respond_to do |format|
format.js
end
end
end
The View (subscribers/create.js.erb)
no clue what goes here to make it return normal AJAX response (or error if it encountered one
1. What do i put in the view to make it return normal ajax response or error? -- Is it even needed to begin with (can I return this without creating such views)
2. Is this the correct way of doing ajax with Rails?
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.
来源:https://stackoverflow.com/questions/8197019/how-to-make-ajax-responses-work-from-the-rails-side