Issue
I have an ajax call to a server side java servlet and a null response is quite valid. However, I also get a 400 error code. The issue with this is that the 400 errors are filling up my report-uri log making it hard to find any 'real' errors. Is there a way to prevent the 400 code.
The ajax call is:
$.ajax({
url : 'NewsDispView',
data : {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssGroupID: sessionStorage.getItem('ssGroupID'),
ssGroupSection: sessionStorage.getItem('ssGroupSection'),
},
type : 'POST',
cache: false,
})
.fail (function(jqXHR, textStatus, errorThrown) {
// alert(jqXHR.responseText);
if(jqXHR.responseText.includes('No News')){
alert("No news");
}else{
alert("News");
}
var marquee = "<span class='glyphicon glyphicon-forward'>";
marquee += " No notices ";
marquee += "<span class='glyphicon glyphicon-forward'>";
$("#newsMarquee").empty();
$('#newsMarquee').append(marquee);
})
.done(function(responseJson1a){
// JSON response to populate the activities table
dataType: "json";
//alert(JSON.stringify(responseJson1a));
//do stuff
})
The servlet return is:
if (newsList == null || newsList.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No News.");
} else {
String json = new Gson().toJson(newsList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
Solution
You can pass your error message as well in JSON format to your ajax call . So , generate your json then pass it like below :
if (newsList == null || newsList.isEmpty()) {
String json = new Gson().toJson(yourjson);
} else {
String json = new Gson().toJson(newsList);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Then , check in your ajax code if the response has the key or not i.e : error
and change your ajax logic accordingly.
Answered By - Swati
Answer Checked By - Timothy Miller (JavaFixing Admin)