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]
CodePudding user response:
try to parse your response text and after join all errors messages from array
const err= JSON.parse(response.responseText).form_error.__all__.join("\n");
alert(err);