user8353997
user8353997

Reputation:

Extracting data from json in JavaScript

I have ajax connection with controller

function changeEmail() {
    $.ajax({
        ...
        contentType: "application/json",
        dataType: "json",
        ...
        error: function (error) {
            var obj = error.responseText;
            console.log('Error: ' + obj);
            console.log('Obj length: ' +  obj.fieldErrors.length);
        }
    });
}

Which in case of error returns a list of errors in json. However, he is not able to refer to this list. https://zapodaj.net/e6354b8c71f4c.png.html I do not know, for example, how to refer to the first element of a list to the

message

variable

Upvotes: 0

Views: 50

Answers (1)

intentionally-left-nil
intentionally-left-nil

Reputation: 8284

Depending on the content-type response from your server, the default response type is probably text/html or some other incorrect content-type.

You have two ways to fix this. First, you can set obj = JSON.parse(error.responseText)

or, you can make sure that the server sets the correct content-type on errors as well.

Upvotes: 1

Related Questions