0


I follow this tutorial (except I put gem 'jquery-rails' in my gemfile ).

The problem, if I click to new post, and fill the form and click to create -> ajax don't work, and show method showing the simple post.

my create.js.erb:

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

create method

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

respond_to do |format|
  if @post.save
    format.html { redirect_to(@post, :notice => 'asdasd') }
    format.js
  else
    format.html { render :action => "new" }
    format.js
  end
end

end

_form.html.erb

    <%= form_for(@post, :remote => true) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

1 Answer 1

2

That's because you're replacing the entire body of your page with the contents

<h1><%= escape_javascript(@post.title) %></h1>

You probably want to append it to some kind of place holder like so

$('#postlist').append('a bunch of html')

Check out the DOM manipulation methods here.

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

5 Comments

if I use $('#showme').html("<h1><%= escape_javascript(@post.title) %></h1>").append("<%= escape_javascript(@post.content) %>"); and I put <div id="showme"></div> in the application.html.erb, nothing changed
@Dodi, so you ran rails generate jquery:install as well? Can you also post the code where you create the html form?
yes, I ran rails generate jquery:install, I edited the questson
@Dodi, everything looks correct to me. Can you verify that you have rails.js and jquery.js in your public/javascripts folder? Do you see any javascript errors before the page reloads?
lol, the rails.js was the original, the jquery:install do not rewrited, I deleted rails.js and recall jquery:install, now its work! thanks for the help

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.