Mirrh Mirrh - 5 months ago 16x
Javascript Question

API call return error result in json format

The below is the javascript code to call API and I would like to present the error result from the API.

var loginData = {
grant_type: 'password',
username: usr,
password: pwd
type: "POST",
url: apiUrl,
data: loginData,
success: function (data) { ... },
error: function (request, status, error) {
display(error message return from API)
}).always(function () {
// ...

And the response from API is "400 Bad request" and the contents as below

"error": "invalid_grant",
"error_description": "The user name or password is incorrect."

Can anyone help me to get this response from the API and display the "error_description" to the user?


If you just want to display the error message to the user (like I think your question is asking) then add something like this to your handler:

function (xhr) {
  res = JSON.parse(xhr.responseText);

Of course you'll need to decide exactly where you want to put this message, and rewrite the HTML and selector appropriately. Or your could just use alert() to display this - it's really up to you.


Since this is a 400 response, it will go to the error handler. In this case, it it returns an xhr object, and the JSON you're seeing should be stored in xhr.responseText. See edited code above.