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.
Also, you shouldn’t have to do the
unless Subscriber.find_by_email(params[:email])in your controller. You should just addvalidates_uniqueness_of :emailto the Subscriber model.In the .erb file that contains the form, you would add the following javascript: