Rails Turbo.visit with post request

638 Views Asked by At

I am trying to initiate a post request programatically.

Turbo.visit('documents/path', { data: { 'turbo-method': 'post' } });

This is not working, it triggers a GET request.

1

There are 1 best solutions below

0
On

On docs is one way for doing a post by JS/Turbo, but based on a Form Element:

«To submit a element programmatically, invoke the HTMLFormElement.requestSubmit() method and pass an <input type="submit"> or <button> element as an optional parameter.»

To do it purely programmatically, the only way I know would be to send a regular post request, without any turbo, to the server, and respond via turbo channel, not turbo stream! My gem does this. Depends on the use case.

In my opinion, the cleaner and preferable way in most cases would be turbo-stream, so this issue could be a feature request. But you also have to send the CSRF token by post.