Search code examples
jsondjango-viewsjquery-ajax

How to correctly display jQuery Ajax Error response text as Alert


I am trying to create an alert from an ajax callback error using:

alert(response.responseText);

However I get the whole string of error text like eg.

"{\"form_error\": {\"__all__\": [\"Data with this Doc and Date already exists.\"]}}"

which is being returned by my Django view.

My ajax function looks like:

    $.ajax({
        type : 'POST',
        url :  ...,
        dateType: 'json',
        data: my_data,
        success : function(response){
             ...
        },
        error : function(response, status, error){
            var err = response.responseText;
            alert("Error: " + err);
        }
        });

Is there a way to only display the relevant text to the user as alert for example:

err = "Data with this Doc and Date already exists."
    alert(err);

How can I display only the relevant info as alert? In my search for a possible solution I have been through numerous SO posts including ways to extract the substring of the above response text but nothing has worked.

PS. I tried to use regex on the Django view side but I could do that with multiple iteration and finally could only come up with:

{"Error": "Data with this Doc and Date already exists"} [Note the curly brackets]


Solution

  • What do you receive as an error response is a json string. It is a stringified json object. You have to parse it to get an acces to json properties. After this you can join all errors messages from array that contains error messages ( in this case only one, but since it is an array it can contain more then one)

    const err= JSON.parse(response.responseText).form_error.__all__.join("\n");
    alert(err);