I am building a web application where users can create a profile and claim a unique username. I wanted to implement it in a way such that as the user is creating the program using the sign up form, I wanted to show them the availability of their name as they were typing it. Thus allowing them to find their perfect username before they hit the submit button.
This means I had to query the database and update a part of the view in my app, as the user was typing their username. This was unlike anything I had ever done before as a new Rails developer. Here’s how I did it using AJAX.
1. Add an event listener to the input event on the username field
In the app/javascript/packs/application.js, I added an event listener for the input event on the username field. When a user types something into the field, the listener triggers the checkUsernameAvailability function.
username.addEventListener("input", checkUsernameAvailability);
2. Use Javascript fetch() in the listener to send an AJAX request to the server
I wrote the checkUsernameAvailability function next. This function sends an AJAX request to the server using the fetch function. It passes the current value of the username field as a query parameter.
function checkSignupLinkAvailability() {
const username = username.value;
fetch(`/programs/check_username_availability?username=${username}`)
.then(response => response.json())
.then(data => {
if (data.available) {
availabilityMessage.innerHTML = "Username is available!";
availabilityMessage.style.color = "green";
} else {
availabilityMessage.innerHTML = "Username is not available!";
availabilityMessage.style.color = "red";
}
3. Configure a custom route for the AJAX request
In the config/routes.rb, I defined a route for the check_username_availability action in the ProgramsController.
get 'programs/check_username_availability', to: 'programs#check_username_availability'
4. Create a custom action in the controller
In the UsersController, I created the check_username_availability action. This action checks if a program with the provided signup link already exists, sets a message, and returns a JSON object containing the message and the availability status.
def check_username_availability
username = params[:username]
user = User.find_by(username: username)
if user
message = "Username is already taken."
available = false
else
message = "Username is available."
available = true
end
render json: { message: message, available: available }
end
When the server responds to the AJAX request, the fetch function in the checkSignupLinkAvailability JavaScript function receives a JSON object containing the message and availability status. The function then updates the message displayed on the page accordingly.
Summary of how to use AJAX in Rails
Using AJAX in your app allows for seamless communication between the client and server, improving the user experience by reducing load times and providing real-time feedback.
It involves the following steps:
Using JavaScript (typically within the fetch method) to send an asynchronous request to the server without a full page reload.
Defining a custom route in your routes.rb file that maps to a specific controller action.
Creating a custom action in the controller to handle the request, perform any necessary logic, and return a response (often in JSON format).
Processing the server response in JavaScript to update the page content or provide feedback to the user.