Ruby on Rails 7 with Ajax (axios)
Ruby on Rails is a fantastic frameworks. Its easy to build your startup with, MVP product and just enjoy ruby. However, it changes frequently and its is challenging to follow up with best practices.
Currently, we have turbo magic build in, but, I’m not yet up to date with this but hope to catch up soon.
Meantime, the issue I faced recently was a AJAX request to backend. Probably now, you can do that with Turbo…but … I don’t know yet how, and needed to deliver a small feature to the client as usual (for yesterday). The feature was simple — check if user exists in the DB from modal.
My simple approach to that, was be just a html modal
and a stimulus controller
with axios
( HTTP client for the browser)
I started by building the modal with daisyui.com — no form, just simple div, input field and a button.
<div data-controller="check-user-email">
<input type="email" data-check-user-email-target="email" name="email" placeholder="Email" />
<div>
<button data-check-user-email-target="submit" name="submit" >Continue</button>
</div>
</div>
The stimulus controller
import { Controller } from "@hotwired/stimulus"
import axios from 'axios' export default class extends Controller {
static targets = ['email', 'submit']
connect() {
this.submitTarget.addEventListener('click', (e) => {
e.preventDefault(); if (this.emailTarget.value.length === 0) {
alert('Please provide an email.')
} else {
axios.get('api/users_by_emails', {
params: {
email: this.emailTarget.value
}, headers: {'ACCEPT': 'application/json'}
}).then(function (response) {
...
}).catch(function (error) {
...
});
}
});
}
}
As you can see above, I’ve used axios
for an Ajax request, simple GET request to the backend with email
attribute
Import Axios (with importmaps)
./bin/importmap pin axios
And thats it. Axios installed and I was happy!
Issue
after installing the newest version of axios@1.1.3
… the AJAX was not working at all… and the error console shown me:
Failed to register controller: check-user-email (controllers/check_user_email_controller) TypeError: Cannot read properties of undefined (reading 'FormData')
at index.js:162:32
I had no idea what is that, and what does that mean. Well, I still don’t have .. I’ve read all the google, stackoverflow but could not find any solution for that.
Fix
To fix this you have to pin the axios
to version 0.27.2.
./bin/importmap pin axios@0.27.2
All the versions greater then 0.27.2 have the FormData
issue.
Why the versions above 0.27.2 are complaining about the FormData, I don’t know. Also, another thing is … my solution probably could have been done without stimulus controller
however, I don’t know that yet how to do that with Turbo. I would be happy to learn that, so please put your suggestion into the comment.
Meantime, happy coding.
Grzegorz