Reputation: 19294
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?
Upvotes: 3
Views: 5190
Reputation: 43298
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.
Upvotes: 6
Reputation: 1988
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.
Upvotes: 0