3

I'm making an ajax request and when it's complete i'm trying to add a div to the page. For some reason, i am unable to get instance variables to work in a .js.erb file.

I have this controller method that gets called

 # PUT /applications/1
  # PUT /applications/1.json
  def update
    @application = Application.find(params[:id])
    @current_app = params[:application]
    @curr_app_id = params[:id]
    @current_app.values.each do |key, val|
        key.values.each do |k,v|
            @curr_app_field_name = k[:field_name]
            @curr_app_field_value = k[:field_type]
        end
    end

    respond_to do |format|
      if @application.update_attributes(params[:application])
        format.html { redirect_to @application, notice: 'Application was successfully updated.' }
        format.json { head :no_content }
        format.js
      else
        format.html { render action: "edit" }
        format.json { render json: @application.errors, status: :unprocessable_entity }
        format.js
      end
    end
  end

which renders this .js.erb file

console.log('name = '+<%= escape_javascript @curr_app_field_name %>); // line 1
console.log('test'); // line 2

But when i leave the instance variable in there, i don't get any output in firebug. I can see in the post request that the console.logs get generated with the correct field name, but nothing appears in the firebug console.

If i remove line 1 completely, it works.

How can i make it so i can access some variables in a .js.erb file?

1
  • You are currently overriding the @curr_app_field_name in loop. Try to inspect whether the last element in the loop is not blank or nil Commented Dec 7, 2012 at 14:21

2 Answers 2

6

You are mixing Javascript and Ruby incorrectly.

Instead of:

console.log('name = '+<%= escape_javascript @curr_app_field_name %>);

you have to do this:

console.log('name = <%= escape_javascript @curr_app_field_name %>');

Explanation:

Suppose @curr_app_field_name == 'foo' then your current code will evaluate to:

console.log('name = '+foo);

but the variable foo doesn't exist and will therefore throw an error. If you do it like I suggest it will evaluate to:

console.log('name = foo');

and everything will work as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

This also works console.log('name = '+ <%= raw @curr_app_field_name) Especially useful if you want to do something like: console.log('name = '+ <%= raw JSON.dump(@application.errors) %>)
0

I think you have to add quotes like this:

console.log('name = '+ "<%= escape_javascript @curr_app_field_name %>");

But if it was just that you may have an error in firebug.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.