Lately i have run into a few applications that are using js.erb
and i am not really sure how to use it ...here is the code below. Can someone help me understand how this works?
in the routes.rb
file
map.resources :player_emails
my controller player_emails_controller.rb
in the create action
def create
@player_email = PlayerEmail.create(params[:player_email])
if @player_email.save
@response_txt = "The player has been emailed."
PlayerEmailsMailer.deliver_pattern_email(@something, @player_email, request.host_with_port)
@error = false
else
@error = true
@response_txt = "Please make sure you entered your name and a valid email address."
end
end
then i have the file player_emails/create.js.erb
$('#player_email_ind').hide();
$('#player_email_submit').show();
$('#player_response_msg').html("<%= escape_javascript @response_txt %>").fadeIn();
<% unless @error %>
$('#player_email_form')[0].reset();
<% end %>
i know what the jquery is going but i dont know how this is doing the ajax
call. Does it just automatically do an ajax
call when there is a js.erb
...can someone explain the way this works and why i dont need a respond_to in the controller action telling it this is format.js
If a js (ajax) request is made it will respond by rendering the js.erb file and viceversa.
This is the default behaviour that is being performed:
respond_to do |format|
format.js{
render :template => 'create.js.erb'
}
format.html{
render :template => 'create.html.erb'
}
end
When the form is submitted, it does a POST to /player_emails
. The resource declaration in routes.rb
ensures the request is handled by PlayerEmailsController#create
.
The controller is responsible for handling each format it receives. In the case of an AJAX call, the format is 'js', and is set by explicitly adding the format string to the end of the URL (/player_emails.js
) or (more likely) by deducing the format from the request header.
In your case, the create
action does not expect anything other than AJAX, so it takes a shortcut and omits the respond_to
and format
blocks. The controller has already figured out that the format is 'js', so when create
is complete it takes the default action of rendering the appropriate template for the format (create.js.erb
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With