Reputation: 2483
I am trying to follow this tutorial to implement sortablejs:
https://www.youtube.com/watch?v=r884jAqAbHY
I'd like to persist the state by sending an ajax update to the server. The tutorial (Rails 6) does this via Rails.ajax
In Rails 7, this causes the console error:
Uncaught ReferenceError: Rails is not defined
What is the "Rails way" of doing asynchronous requests in Rails 7?
Upvotes: 2
Views: 1590
Reputation: 1244
You can use https://github.com/rails/request.js#how-to-use
e.g.
import { FetchRequest } from '@rails/request.js'
....
async myMethod () {
const request = new FetchRequest('post', 'localhost:3000/my_endpoint', { body: JSON.stringify({ name: 'Request.JS' }) })
const response = await request.perform()
if (response.ok) {
const body = await response.text
// Do whatever do you want with the response body
// You also are able to call `response.html` or `response.json`, be aware that if you call `response.json` and the response contentType isn't `application/json` there will be raised an error.
}
}
Upvotes: 0
Reputation: 2483
Fetch works - I don't know if it is the "Rails way". . .
fetch("URL", {
method: "PATCH",
headers: {
"X-CSRF-Token": document.querySelector("[name='csrf-token']").content,
},
body: data,
});
Upvotes: 3