0

Was there a change in how JQuery 3 and Jquery 1 handled remote form errors on Rails?

In the past, (Rails 6, Zurb Foundation, Jquery 1), the code below would work. A user would submit a form, they'd forget their name, we'd set the @error_message variable and then render a 400 and return to stop the action. When it got to the partial (send_appointment_request.js.haml), the browser alert would pop-up the error message.

Now, (Rails 6, Bootstrap 5, Jquery 3), if we use render status: 400 and return there is an error in the console and the browser's alert pop-up never opens to show the @error_message variable. The code gets to the partial, but it never executes.

If we just RETURN and don't use the "render status: 400 and return" part, then the error message shows, because it comes through as a 200 status code.

Just confused why the code used to work (we'd render a 400 and the browser would still pop-up the error message) and now the code errors.

Two screenshots are shown to help explain the issue.

EDIT: I'm guessing this has to do with the 400 response kicking off the error callback of $.ajax(), which is what sent the remote form. But this never happened before with Jquery 1 or Foundation.

So does this mean I will always need to reply with 200 status codes, even if the data sent is invalid (422 error)?

Better stated. Why does Rails only evaluate my javascript code in the partial when it's a 2XX response, and not when it's a 4XX response?

def send_appointment_request
  respond_to do |format|

    format.js do 

      if params[:name].blank?
        @error_message = "Error: You forgot to include your name. Please try again."
        render status: 400 and return
      end
        
      #
      # Lots of Code Removed
      #

      @success_message = "Thanks for submitting your appointment request!"
    end
  end
end

send_appointment_request.js.haml

- if @error_message
  alert("#{sanitize @error_message}");

- else
  alert("#{sanitize @success_message}");

This is the error message in the console:

400 error

and then this is the code that shows up in the error:

code issue

2
  • 1
    This doesn't seem to involve Bootstrap at all. I suggest removing that tag, and maybe jQuery as well. Also, please don't annotate edits. It's all in the revision history anyway and doesn't add clarity to future readers. Just revise as though writing anew.
    – isherwood
    Commented Jun 27 at 14:37
  • Can you post your form and the rails logs too? BTW if your js is actually as simple as shown you can just use render js: "alert(#{sanitize @error_message});" Commented Jun 27 at 17:53

0