John was the one who provided the correct answer, but I'll go into more detail:
Are you familiar with the fundamental concept of ajax? Let's say you want to allow users to create comments in a more dynamic way.
In a rails application, you can handle POST requests in your CommentsController
like this:
def create
@comment = Comment.new(params[:comment])
respond_to do |format|
render.js
end
end
So, when an ajax request is sent from the client side (using jquery/javascript) to the CommentsController
, it will respond with the .js
format, triggering the _create.js.erb partial.
This partial will then display the new comment by appending it to the list of comments, like this:
$('.comments').append("<%=j render @comment %>");
Now, regarding the j or escape_javascript method:
A malicious user could submit a comment with harmful javascript code that could potentially be executed on the page, unless you use the j
method, which
Escapes carriage returns and single and double quotes for JavaScript segments.
and prevents the code from executing in the browser.