2

After I validate user login, if it failed it will show the following error message

jquery

console.log('Full error  = ' + JSON.stringify(showError));
console.log('test 1 =' + showError.responseText);

Error message

Full error  = {"readyState":4,"responseText":"{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}","responseJSON":{"error":"invalid_grant","error_description":"The user name or password is incorrect."},"status":400,"statusText":"Bad Request"}


test 1 ={"error":"invalid_grant","error_description":"The user name or password is incorrect."}

I want to display only The user name or password is incorrect message only

I already check this jQuery - Get value from JSON Stringify link

Liam neesan
  • 1,949
  • 4
  • 27
  • 56

2 Answers2

3

You have to parse the responseText property since it's a JSON string.

console.log(JSON.parse(showError.responseText).error_description);

// or using bracket notation
console.log(JSON.parse(showError.responseText)['error_description']);

var showError = {"readyState":4,"responseText":"{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}","responseJSON":{"error":"invalid_grant","error_description":"The user name or password is incorrect."},"status":400,"statusText":"Bad Request"} ;

console.log(JSON.parse(showError.responseText).error_description);
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178
2

You can use JSON.parse method to parse a json data in string format.It will return a json object.In your case.

var response = JSON.stringify('{"readyState":4,"responseText":"{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}","responseJSON":{"error":"invalid_grant","error_description":"The user name or password is incorrect."},"status":400,"statusText":"Bad Request"}
')
var error_message = response.responseText.error_description

error_message variable contains your error message