ozbilgic
ozbilgic

Reputation: 81

Why doesn't ajax show the new data on the page?

I am creating a new application in Ruby on Rails and using the line below:

rails generate scaffold User name

I change the controller as follows:

class UsersController < ApplicationController
  def index
    @users = User.all
    @user = User.new
  end
  # ...

The index view (app/views/users/index.html.erb) contains:

<h1>Users</h1>

<ul id="users">
  <%= render @users %>
</ul>

<br>

<%= form_with(model: @user) do |f| %>
  <%= f.label :name %><br>
  <%= f.text_field :name %>
  <%= f.submit data: { "disable-with": "Saving..." } %>
<% end %>

The app/views/users/_user.html.erb partial contains the following:

<li><%= user.name %></li>

I am changing the create action on the controller as follows:

# app/controllers/users_controller.rb
# ......
def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.js #THIS IS ADDED
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

I created the file named "create.js.erb" at "app/views/users/" and added the line below: app/views/users/create.js.erb:

$("<%= escape_javascript(render @user) %>").appendTo("#users");

When I save a new user, database registration occurs, but the user is not displayed on the page.

Ruby: ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
Rails: Rails 6.0.2.2

Upvotes: 1

Views: 26

Answers (1)

Amit Patel
Amit Patel

Reputation: 15985

Check your browser's console what error you are getting. I am sure there must be some javascript error in the browser console.

I suppose you wouldn't have included jquery in your application.js. You need to do explicitly as it doesn't get included automatically with rails 6 app.

Upvotes: 2

Related Questions