Reputation: 9858
This question is related to the previous one, when I click over an anchor
<a href="#" id="Email">send email</a>
it calls servlet using json
$("#Email").click(function() {
var option={
"action":"sendEmail"
};
$.getJSON('StudentManagementServlet',option, function(hasEmail) {
if(hasEmail == false){
// //view form to let user enter his email
$("#CommViaEmail").fadeIn("normal");
}
});
});
in servlet I handle the request
if (action != null && action.equals("sendEmail")) {
//open connection to db
con.setAutoCommit(false);
String email = ParentManagement.getParentEmail(con, stdNo);
if (email != null) {
String commResult = createAccountAndSendEmail(con, parentNo, email);
request.setAttribute("result", commResult);
request.setAttribute("incp", "ResultPage");
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response); //doesn't make forward!!!!!
System.out.println(">>send email DONE!!");
con.commit();
return;
} else {
boolean hasEmail = false;
String json = new Gson().toJson(hasEmail);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
The problem here is if user has an email, then I send an email but request dosn't forward to result page, even the print statement is printed " System.out.println(">>send email DONE!!");" ??
Upvotes: 0
Views: 386
Reputation: 3084
You are making an AJAX request from the client and are trying to 'forward' that request in the server side.
AJAX requests DONT refresh the page. The hasEmail
variable in javascript function will be a string containing the HTML of the index.jsp
.
Upvotes: 0
Reputation: 1108802
You need to let JS/jQuery do that job. Let the servlet write true
as JSON result and in JS do
if (hasEmail) {
window.location = 'index.jsp';
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
Or when you want to control the URL yourself, add the new location to the JSON
Map<String, Object> data = new HashMap<String, Object>();
data.put("hasEmail", true);
data.put("location", "index.jsp");
// ...
with
..., function(data) {
if (data.hasEmail) {
window.location = data.location;
} else {
$("#CommViaEmail").fadeIn("normal"); //view form to let user enter his email
}
}
Upvotes: 1