Issue
I'm doing the login for our system and the index.html has this script,
<script>
$('#navbar').load('navbar.html');
$('#errorMessage').hide();
$("#loginBtn").click(function() {
$.post('http://localhost:8080/NewDesignV1/login.action',
{
username : $("#username").val(),
password : $("#password").val()
}
,'html');
});
</script>
The post location is a servlet, I need to go to this servlet so I could get the data from index.html, manipulate it and redirect it to a JSP page.
My problem is, I can get the data from ajax post but it won't redirect to a JSP page when I use
request.setAttribute("key", value);
request.getRequestDispatcher("studentprofile.jsp").forward(request, response);
Solution
The reason is that your have call it via $.post
,so it's an ajax
method,
in fact request.getRequestDispatcher("studentprofile.jsp").forward(request, response);
is working and you can get it
$("#loginBtn").click(function() {
$.post('http://localhost:8080/NewDesignV1/login.action',
{
username : $("#username").val(),
password : $("#password").val()
},
function(data){
console.log(data);//you can get the redirect jsp context
},
,'html');
});
In order to let the studentprofile.jsp
display,you need to avoid using $.post
, you can create a form and then submit the form:
$("#loginBtn").click(function() {
var form = document.createElement("form");
document.body.appendChild(form);
$(form).append("<input type='hidden' name='username' value='"+$("#username").val()+"'>");
$(form).append("<input type='hidden' name='password' value='"+$("#password").val()+"'>");
form.action="http://localhost:8080/NewDesignV1/login.action";
form.method="post";
form.submit();
$(form).remove();
});
Answered By - lucumt
Answer Checked By - Candace Johnson (JavaFixing Volunteer)