I'm doing some ajax first time... code:
jQuery
form_ajax_promise = $.ajax({
type : "POST",
url : '/orders/create_or_update',
dataType: 'json',
contentType: 'application/json',
data : JSON.stringify(params)
})
form_ajax_promise.then(
function(response) {
formSuccess(response)
},
function(response) {
formFailure(response)
}
)
Controller
def create_or_update
if @object.save
# corresponds with formSuccess
render json: {"id" => @order.id}, status: 200
else
# corresponds with formFailure
render json: {"errors"=> @order.errors.full_messages}, status: 400
end
end
The success path works well. In testing the failure route, assuming that formFailure is just a simple function...
function formFailure(response){
console.log("successfully inside of formFailure")
}
What I'm noticing is happening is that the console shows the appropriate log message as above, but also shows me an error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
Is this error supposed to happen? I felt like since I provided an adequate fail in the $.then it shouldn't?
EDIT
Apologies for the confusion, this is NOT a case of multiple render/re-direct, I was just being lazy and cutting out the other code, since I was only trying to describe fail behavior. My mistake. Code is edited above.
Maybe something like this will do. This will return you success when @order is saved successfully and error when @order is invalid
def create_or_update
# Your code here to create or update @order
if @order.save
# corresponds with formSuccess
render json: {"id" => @order.id}, status: 200
else
# corresponds with formFailure
render json: {"errors"=> @order.errors.full_messages}, status: 400
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With