What is AJAX and why it is created? AJAX is amazing technology allows parts of a webpage to update without reloading the entire page, making the user experience much faster and more dynamic.

In this post, we'll learn how to set up AJAX in a Rails app with a couple of examples of submitting a form and updating content on the page in real time.

What Actually is AJAX?

AJAX stand for Asynchronous JavaScript and XML is a technology that enables web pages to send and receive data from a server asynchronously.

Means Instead of refreshing the entire page, it updates specific parts, which improves the performance and user experience as well.

In Rails, AJAX is often used to:

  • Submit forms without reloading the page.
  • Fetch and display dynamic content.
  • Update specific sections of a webpage in real-time.

So now, let’s learn how to make AJAX call in your Rails app.

Submitting a Form Without Refreshing the Page

To demonstrate AJAX in Rails, we’ll create a simple app where users can submit comments to a post. The comments will be added to the page without refreshing.

i) Set Up the Rails Project

Follow this step if you don't have rails project ready for testing AJAX otherwise, skip to next section.


rails new ajax_demo
cd ajax_demo

Generate the model and migrate the database:


rails generate model Comment content:string
rails db:migrate

This creates a comments table with a content column to store the comment text.

ii) Create the Comments Controller

Next, generate a controller to handle comments:


rails generate controller Comments

Update app/controllers/comments_controller.rb to handle displaying and creating comments:

ruby
class CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end

  def create
    @comment = Comment.new(comment_params)
    if @comment.save
      respond_to do |format|
        format.html { redirect_to comments_path }
        format.js   # Respond with JavaScript if it's an AJAX request
      end
    else
      render :index
    end
  end

  private

  def comment_params
    params.require(:comment).permit(:content)
  end
end

Here, we handle two formats:

  • HTML for normal requests.
  • JS for AJAX requests.
iii) Create the JavaScript Response

When the form is submitted via AJAX, Rails will look for a file named create.js.erb. This file is responsible for updating the page dynamically.

Create app/views/comments/create.js.erb and add:

javascript
$("#comments").append("<%= j render @comment %>");
$("input[type='text']").val("");

This script appends the new comment to the list and clears the text field.

Updating a Partial with AJAX

To display comments on the page, we need a partial template that can be updated via AJAX. In app/views/comments/index.html.erb, render the comments and display a form:

erb
<h2>Comments</h2>

<div id="comments">
  <%= render @comments %>
</div>

<%= form_with model: Comment.new, remote: true do |form| %>
  <div>
    <%= form.label :content, "Add a comment" %>
    <%= form.text_field :content %>
  </div>
  <%= form.submit "Post Comment" %>
<% end %>

What’s Happening Here?
  • remote: true: Makes the form submit via AJAX instead of a traditional request.
  • render @comments: Displays all the comments using a partial.

Create the _comment.html.erb partial in app/views/comments/:

erb
<p><%= comment.content %></p>

How to Submit a Rails Form Without Refreshing the Page

By combining Rails’ form_with helper and AJAX, you can submit a form without a page reload. Let’s walk through the steps once more:

  1. Create a form using form_with remote: true.
  2. Handle the request in the controller and respond with JS.
  3. Update the DOM dynamically using a .js.erb file.

With these steps, you can seamlessly submit forms and display new data without interrupting the user’s experience.

Further Reading

To dive deeper into AJAX and Rails, check out these resources:

By following the steps outlined in this post, you can build dynamic, responsive web applications with ease.

Let me know the feedback in comments below. Thanks


Comments(0)