Search code examples
ruby-on-railshttp-status-code-204

Rails 6 - on a POST is it safe to rely on 204 (No Content) to let Jquery update the same page while a record is created in background?


Background: in Rails 5+, a POST route without an associated View now simply returns a 204 status code to the browser (instead of raising a ActionView::MissingTemplate exception as done before Rails 5). Which, as far as I understand it, tells all browsers to "stay on the same page".

For UX reasons, on a certain form when the user clicks "submit" it POSTs the form data, and ALSO triggers Jquery to do some updating to the page.

While it seems to work fine, both on development and production, are there any adverse implication to combining the form submit returning a 204 AND having jQuery update info on the page?


Solution

  • Which, as far as I understand it, tells all browsers to "stay on the same page".

    This is not correct. 204 is just the server telling the client "I did what you asked but I don't have anything more to tell you about it". It does not "tell browsers to stay on the same page" - if you have prevented the default action (submitting the form) and are sending an asynchronous (AJAX) request the browser will not do anything at all with response no matter what status code you respond with. Its up to your XHR handler to do whatever it wants with the response.

    If you actually submitted the form (syncronously) and got a 204 - No Content response the browser will render a blank page or one of those error pages with sad dinosaurs. Its only actually the 3XX redirection status codes together with the Location header which cause redirects.

    I would say Rails usage of 204 is pretty decent for a default but its not really the correct response. Use 201 Created if the resource is created immediatly or 202 Accepted if the resource is created in the background. The differences here however are largely semantical and for example jQuery just equates all non 4XX and 5XX to "good" response codes while the rest trigger errors.