Reputation: 1174
In my webapp users can add other users to their projects. A user can type in an email address and it will ask the server, via post, whether the user exists or not. If the user exists, it will send back the DTO representing that object. If the user does not exist, it should send back null.
I want the null response to trigger the success callback to differentiate it from any other server-side error that could occur. I'm using Spring MVC on the server side. However, returning null triggers the error callback. Any suggestions on how to accomplish this?
Upvotes: 0
Views: 1356
Reputation: 4581
From http://api.jquery.com/Ajax_Events/
success
This event is only called if the request was successful (no errors from the server, no errors with the data).
error
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
Since you have an error on the data, error() is fired. Try to wrap the null response with valid data format you specified on the ajax call (e.g, json, jsonp, ...).
Upvotes: 2
Reputation: 95578
Instead of returning null
you should return an object that says that the request was unsuccessful or that the user does not exist. null
is not valid JSON (this is why the error
callback is being called). So, you can return something like this:
{
"successful": false,
"message": "User does not exist",
"userDTO": null
}
This should be pretty trivial in Spring MVC; you can simply add these to the model when you return it, or use a POJO that contains this information and return that instead.
Conversely, for a successful request, you would have:
{
"successful": true,
"message": "User found",
"userDTO": {
"firstName": "Guybrush",
"lastName": "Threepwood"
}
}
Upvotes: 4