Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does js.erb work

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

like image 985
Matt Elhotiby Avatar asked Jan 05 '11 17:01

Matt Elhotiby


2 Answers

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
like image 190
mark Avatar answered Oct 16 '22 09:10

mark


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).

like image 32
zetetic Avatar answered Oct 16 '22 07:10

zetetic