How to make Ajax calls — The Rails way
I’ve recently read an article called How to make AJAX calls in Rails 5.1 and I have to say that I was disappointed. The article was technically correct. It mentioned three different ways to make Ajax calls, but it did not mention the “Rails way”.
Ajax calls — The Rails way
So what is the “Rails way” for making Ajax calls? You don’t write any JavaScript and you let Rails make Ajax calls for you!
Rails ships with an awesome unobtrusive JavaScript adapter called rails-ujs. It is included in all new Rails applications. It provides us different features and one of them is seamless Ajax support.
Let’s see it in the following code samples.
Link with Ajax GET request
<%= link_to "New user", new_user_path, remote: true %>
Link with Ajax DELETE request
<%= link_to "Delete user", user_path(@user), remote: true, method: :delete %>
Form submitted via Ajax
<%= form_for @user, remote: true do |form| %>
...
<% end %>
Even better form submitted via Ajax
<%= form_with model: @user do |form| %>
...
<% end %>
Checkbox which sends an Ajax request after it’s value changes
<%= check_box_tag dom_id(todo, :checkbox), "", data: { url: toggle_todo_path(todo), remote: true } %>
Ajax link without Rails helpers
<a href="/users/new" data-remote="true">Add user</a>
As you can see, it is usually enough to add remote: true
to view helpers and rails-ujs will submit generated links, forms and other elements via Ajax. It will handle everything. Even the CSRF tokens.
Also, as you might or might not notice, you don’t even have to use remote: true
if you use form_with
, because all forms created by form_with
are submitted via Ajax by default.
Learn more about
form_with
in Rails 5.1’s form_with vs. form_tag vs. form_for.
Processing request made by rails-ujs
Now you know how to create Ajax requests without any JavaScript. But how do you process them on the server?
Actually, you process them in the same way as standard HTML requests. The only difference is that you will respond with JavaScript instead of HTML.
# app/views/new.js.erb$("[data-placeholder~=user_form]").html("<%= j render "form", subscription: @user %>");
This template will generate a JavaScript code which finds the placeholder element and replaces it’s content with the provided HTML. This technique is called SJR (Server-generated JavaScript Responses) and you can learn more about it in my previous post.
Conclusion
As you can see it is easier to use tools which Rails provides us. Making Ajax calls is no exception. Of course that there are use cases for manual Ajax requests, especially if you use client side rendering, but in my experience they are rare and using SJR is pretty much enough.
Do you want to know more? Then check out my course about Ajax on Rails or subscribe to my newsletter and shoot me an email!