2
votes

I'm following this tutorial about making an Ajax request on Rails:

http://net.tutsplus.com/tutorials/javascript-ajax/using-unobtrusive-javascript-and-ajax-with-rails-3/

made _form remote: <%= form_for(@post, :remote => true) do |f| %>

My scripts are loaded:

  <script src="/assets/jquery.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>

Added format.js to posts_controller.rb:

  def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.js
      else
        format.html { render action: "new" }
        format.js 
      end
    end
  end

Created create.js.erb:

$('body').html("<h1><%= escape_javaScript(@post.title) %></h1>").append("<%= escape_javaScript(@post.content) %>");

But when I click the submit button nothing happens in the view but the posts are being created. I just get this in the terminal:

Started POST "/posts" for 127.0.0.1 at 2012-02-06 12:58:02 +0800 Processing by PostsController#create as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"m4BT19I9aUQ+FwGD3Ub9WqKJc0IqjsPpD8+nOyQNhjo=", "post"=>{"name"=>"asdsad", "title"=>"sadassad", "content"=>"adasdadadad"}, "commit"=>"Create Post"} (0.2ms) begin transaction SQL (86.7ms) INSERT INTO "posts" ("content", "created_at", "name", "title", "updated_at") VALUES (?, ?, ?, ?, ?) [["content", "adasdadadad"], ["created_at", Mon, 06 Feb 2012 04:58:02 UTC +00:00], ["name", "asdsad"], ["title", "sadassad"], ["updated_at", Mon, 06 Feb 2012 04:58:02 UTC +00:00]] (120.0ms) commit transaction Rendered posts/create.js.erb (307.9ms) Completed 500 Internal Server Error in 528ms

ActionView::Template::Error (undefined method `escape_javaScript' for

<#:0xb78ecd0>):

1:    $('body').html("<h1><%= escape_javaScript(@post.title) %></h1>").append("<%= escape_javaScript(@post.content) %>");  

app/views/posts/create.js.erb:1:in _app_views_posts_create_js_erb__76139275_96235900'
app/controllers/posts_controller.rb:45:in
create'

Rendered /home/alex/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (9.9ms) Rendered /home/alex/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.1ms) Rendered /home/alex/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.1/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (19.1ms)

Any suggestions to fix this?

1

1 Answers

4
votes

There's a typing error in that tutorial; escape_javaScript should be escape_javascript (lower case)

See also: escape_javascript()