How to render AJAX ES6 form responses?

I’m trying to figure out how to best implement AJAX responses for form_with.

It seems that Server-generated Javascript Responses (SJR) were recommended since 2013 (also see this 2019 post), but Sprockets isn’t configured to handle JS in Rails 6 by default and my understanding is that such server-rendered JS views (which would reside e.g. at app/views/messages/create.es6.erb) can only be managed by Sprockets? Does this mean SJRs are on the way out, or that Webpacker can handle SJRs?

I also read here that new things are coming to address how Basecamp approaches JS in 2020 (incl. a Turbolinks 6 release).

So what is the current and upcoming “omakase” pattern to render AJAX ES6 form responses? Should I just go for temporary solutions for now while we wait for announcements?


(For more context: I took over a Rails 4.2 app which has since been upgraded to 6, and I’m trying to figure out how to add form_with forms with remote AJAX calls, while being able to use ES6. The app doesn’t yet have Turbolinks, hopefully will be added after more regression testing, but now has Webpacker. It still needs to be upgraded from Sprockets 3 to 4, so the Sprockets JS doesn’t handle ES6 yet, and I don’t yet know whether it should or if all JS should move to Webpacker.)

1 Like

Hi Sébastien,

Your question is very valid, this rather old topic discusses that at large:

If you don’t want to introduce websockets into the mix, then using the turbolinks_render gem by Jorge is probably your best bet. There’s a few other solutions mentioned in that thread.

If you however can add Action Cable then you can refer to the Optimism gem, which is using CableReady underneath.

StimulusReflex has a section on working with forms that you can also have a read at.

Hope that helps : )

2 Likes

Thanks a lot Martin, I’ll have a lot at these resources.

I just wanted to reply to this part:

server-rendered JS views (which would reside e.g. at app/views/messages/create.es6.erb ) can only be managed by Sprockets

This is actually not true. Sprockets only applies to /app/assets, not app/views.

BUT you do need to use the right mime-type in your filename: create.js.erb.

Hey @sedubois

I think that the SJR will be deprecated soon with the new version of Tubolinks. If you do some console inspect in the new product of basecamp ‘HEY’, they stop using it and use a full HTML over the wire.

To manipulate the HTML, they use <template …>, I have written a post about it:

So to be future proof and make your upgrade easier, I think it’s safer to stay away from the SJR

2 Likes