Hi,
This problem bugs me for a while because I don't know the best practice, so I wanted to ask it here.
I have a single $.ajax promise chain on my forms. Basically, just this:
- $.ajax({ dataType: 'json'
- }).done(function(response))
- }).fail(function(response))
- }).always(function(response))
- ));
I respond JSON in backend with 200-OK header.
- return \Response::json(['message' => 'Hello world'], 200);
When I do the following:
- done(function(response) {
- alert(response.message); // Hello world
- })
It works properly. However, when I change the response code of the response into something non-200
- return \Response::json(['message' => 'Hello world'], 406);
and check it like:
- .fail(function(response) {
- alert(response.message); // Response object
- })
response becomes the "response object". It doesn't get .message attribute by default.
To solve this, I tried the following:
A. Return 200 OK all the time, send a 'status' => 'error' parameter with JSON.
Problem: Everything is being done in .done callback, it requires .fail callback to check if server had an error (e.g syntax error) and were unable to send JSON.
B. Send status codes normally. Instead of returning JSON, return attributes on response header.
Problem: Requires backend changes to catch all exceptions and append exception messages into response header, sounds bad practice.
C. Return status codes normally, send a 'status' => 'error' parameter with JSON, parse the response object.
Problem: It requires the following:
- .fail(function(response))
- {
- var json = JSON.parse(response.responseText)
- alert(json.error.message);
- }
Well, those are all annoying. What I want is a reliable way to make sure both promises and JSON works properly. Final form should be this:
- $.ajax({ ... })
- .done(function(response)) {
- alert(response.message); // Something success message
- })
- .fail(function(response)) {
- alert( response.message || "Unknown error - check back again");
- })
- .always(function(response) {
- // Basic cleanup
- });
Could anyone help?