Reputation: 475
I'm working in Ruby on rails. I have successfully been able to set up a form that will render my create.js.erb. But I'm wondering if there is any way to check if the form fails to make an object? Right now, if it fails it does nothing.
My controller looks like this:
if @expansion.save
respond_to do |format|
format.js
format.html { render action: "index", notice: 'Book was successfully created.' }
format.json { render json: @book, status: :created, location: @book }
end
else
respond_to do |format|
format.js
format.json { render json: @book.errors, status: :unprocessable_entity }
format.html { render action: "index", notice: 'something went wrong' }
end
end
Is there a way for me to pick up the error in create.js.erb ?
Upvotes: 5
Views: 5319
Reputation: 4604
You will still have access to the @expansion instance variable inside of create.js.erb. You can execute js code dependent on the existence of @expansion.errors - for example:
<% if @expansion.errors %>
alert("You have the following errors: <%= @expansion.errors %>");
<% else %>
// js code for successful save
<% end %>
Upvotes: 2
Reputation: 11896
From the Rails guides on Ajax:
$(document).ready ->
$("#new_article").on("ajax:success", (e, data, status, xhr) ->
$("#new_article").append xhr.responseText
).on "ajax:error", (e, xhr, status, error) ->
$("#new_article").append "<p>ERROR</p>"
In short, you should have your Ajax function check to see if the server responds with a success or failure.
Upvotes: 1