What does the j function in Rails do?

JavascriptRuby on-RailsAjaxPartial Views

Javascript Problem Overview


I just came across a blog that mentions a j function in Rails. They were using it to do ajax style page updates.

$('#cart').html("<%=j render @cart %>");

I get they are using partials to render the cart partial, but whats the point of j? I've found some articles that say it converts the string to something JavaScript will accept, but what does that mean?

Javascript Solutions


Solution 1 - Javascript

Peter actually posted the correct answer. But I will try to elaborate:

I guess you are familiar with the basic concept of ajax? Lets say you want to be able to create comments in an ajaxy fashion. In rails you may respond to POST requests in your CommentsController via:

def create
  @comment = Comment.new(params[:comment])
  respond_to do |format|
    render.js
  end
end

This means if an ajax request from the client (via jquery/javascript) is submitted to the CommentsController it will recognize the format (.js) and respond with the _create.js.erb partial. The partial would then render the new comment with something like this:

$('.comments').append("<%=j render @comment %>");

Now to get to the j or escape_javascript method: Some evil user may submit a comment containing (malicious) javascript which would be executed on your page unless you make use of the j method which > Escapes carriage returns and single and double quotes for JavaScript segments.

and therefore prevents the execution of the code in the browser.

Solution 2 - Javascript

>escape_javascript(javascript) > > Escapes carriage returns and single and double quotes for JavaScript segments. > > Also available through the alias j().

From the the rails docs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTyler DeWittView Question on Stackoverflow
Solution 1 - JavascriptwppView Answer on Stackoverflow
Solution 2 - JavascriptPeter SobotView Answer on Stackoverflow