Set Ajax response on jsp not working - java

Last few hours i am trying to solve this but i can not.I am sending ajax request using jquery and based on response i set data on jsp.actully i am checking login detail so if login fail it set error message on label problem is that error message is set for few second and removed i mean to say error message is set for few second i want that if login fails the message is set on label still user enter valid details
thanks in advance
Here is my code
LoginDemo.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="css/firstpage.css" rel="stylesheet" type="text/css" /><!-- <style> -->
<script src="js/jquery.min.js"></script>
<title>Insert title here</title>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "AddInspServlet",
cache:false,
data: { userid: $('#username').val(), password: $('#password').val(),btn:$('#submit').val() },
success:function(data,textstaus){
alert("success:"+data);
if(data == "no"){
alert( document.getElementById("error").innerHTML);
document.getElementById("error").innerHTML= "UserName OR Password is incorrect";
alert( document.getElementById("error").innerHTML);
}else{
location.href = 'Home.jsp';
}
},
error:function(data){
alert("error"+data);
},
});
});
});
</script>
</head>
<body>
<form id="login" name="Loginform" method="post">
<h1><b>Log In</b></h1>
<fieldset id="inputs">
<input id="username" type="text" placeholder="Username" autofocus required>
<input id="password" type="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="login">
Forgot your password?
</fieldset>
<label id="error" style="color: red;font: bolder; font-size: 18px;">
</label>
</form>
</body>
AddInspServlet
Here i m adding code which server executed and retrieve response
if(btn.equals("login"))
{
System.out.println("***** login condition checking ******");
String password =request.getParameter("password");
UserVO v =op.loginCheck(username, password);
if(password.equals(v.getPassword()))
{
System.out.println("inside true condition");
HttpSession session = request.getSession();
session.setAttribute("userid",v.getUser_id());
session.setAttribute("username",v.getUsername());
session.setAttribute("user", v.getFirst_name()+" "+v.getLast_name());
session.setAttribute("roleid", v.getRole_id());
// response.sendRedirect("Home.jsp");
System.out.println("submitting data success fully");
out.print("yes");
}
else
{
System.out.println("false condition");
out.print("no");
}
}

Get rid of the form tags.
By adding a type="submit" input element without using the action attribute in the form tag, the page will be reloaded.
Or you could keep the form tags and change the type of the submit button to type="button". The form will then not be executed and the page will not reload.

It would be better if you be more specific about the problem. I assume your problem is Label is getting displayed for few seconds and then get disappeared. Is that is true? then try to return "false" inside you data == "no" logic.
Thanks.

Related

not able to get json back to jsp from servlet in ajax code

I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.

On Click of radio button navigate to new JSP

This is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>Select Payment Method<BR><BR>
<font size=""><marquee behavior="alternate">PAYMENT GATEWAY</marquee></font>
<form action="S2ShowPay.jsp" method="post">
<input type="radio" value="NET BANKING" name="payment" >NET BANKING<br><br>
<input type="radio" value="DEBIT CARD PAYMENT" name="payment">DEBIT CARD<BR><br>
<input type="radio" value="CASH ON DELIVERY" name="payment" >CASH ON DELIVERY<br><br>
<input type="submit" value="NEXT"/>
</form>
</body>
</html>
I want to navigate to netbanking.jsp when I click on Net Banking radio button and Debit.jsp repectively, using only jsp and some javascript.
Please help.
Im not sure what's your expected result, Perhaps you can try this. Correct me if im wrong.
Using location.href
function fnPayment()
{
if(document.getElementById("a").checked ==true || document.getElementById("b").checked ==true)
{
location.href = "http://www.google.com"; //your jsp file
}
}
</script>
<input type="radio" value="NET BANKING" name="payment" id="a">NET BANKING<br><br>
<input type="radio" value="DEBIT CARD PAYMENT" name="payment" id="b">DEBIT CARD<BR><br>
<input type="radio" value="CASH ON DELIVERY" name="payment" id="c">CASH ON DELIVERY<br><br>
Using response redirect
Since you have created S2ShowPay.jsp, you can pass parameter to it once you clicked next button and put response redirect based on the parameter.
<input type="radio" value="NET" name="payment" >NET BANKING<br><br>
<input type="radio" value="DEBIT" name="payment">DEBIT CARD<BR><br>
<input type="radio" value="CASH" name="payment" >CASH ON DELIVERY<br><br>
S2ShowPay.jsp
String payment_ind = request.getParameter("payment");
if(payment_ind.equals("NET") || payment_ind.equals("DEBIT") )
{
response.sendRedirect("netbanking.jsp");
}
Add this code within head tag:
<script type="text/javascript">
function redirectPage(use,rname){
for (var val = 0, r1=use.elements; val < r1.length; val++)
if(r1[val].name==rname&&r1[val].checked)
use.action=r1[val].value;
}
</script>
Change your form tag like this:
<div>
<form action="#" method="post" onsubmit="redirectPage(this, 'r1');">
<input type="radio" name="r1" value="netbanking.jsp">NET BANKING<br><br>
<input type="radio" name="r1" value="Debit.jsp">DEBIT CARD<BR><br>
<input type="radio" name="r1" value="cashondelivery.jsp">CASH ON DELIVERY<br><br>
<input type="submit" value="Next"/>
</form>
</div>
Select the desired radio button and then clicking Next button will redirect to respective page.

how to redirect to success page through servlet using ajax?

I have a jsp page which takes user name and password and then it redirect to a servlet. Below is jsp code,
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>DeliverMe</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery Version 1.11.0 -->
<script src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-login').click(function() {
var userName = $('#userName').val();
var password = $('#password').val();
var datastr='userName='+userName+'&password='+ password;
$.ajax({
url : 'LoginCheck',
data :datastr,
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
},
error:function(url){
window.location = url;
}
});
});
});
</script>
</head>
</head>
<body>
<div class="container">
<span style="color: #000099"><center><h2>DeliverMe Admin Panel</h2></center></span>
<div id="loginbox" style="margin-top:50px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Sign In</div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12"></div>
<form id="loginform" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="userName" type="text" class="form-control" placeholder="username or email">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="password" type="password" class="form-control" name="password" placeholder="password">
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm- 12 controls">
<a id="btn-login" class="btn btn-success">Login</a>
</div>
</div>
<span id="ajaxGetUserServletResponse" style="color: red;"></span>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Then my servlet checks user name and password and if it is wrong then it gives error text but if it is true then it should be redirect to success page. But it doesn't effect. Below is servlet code,
if(db.loginCheck(userName, password))
{
request.getRequestDispatcher("/main.jsp").forward(request, response);
}else
{
String greetings = "Invalid Username/Password";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
I got solution. I have changed response of my servlet like this,
if(db.loginCheck(userName, password))
{
response.getWriter().write("1");
}else
{
greetings = "Invalid Username/Password";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
and on my jsp page i have put this,
<script type="text/javascript">
$(document).ready(function() {
$('#btn-login').click(function() {
var userName = $('#userName').val();
var password = $('#password').val();
var datastr='userName='+userName+'&password='+ password;
$.ajax({
url : 'LoginCheck',
data :datastr,
success : function(responseText) {
if(responseText == "1"){
window.location.assign("/main.jsp");
}else{
$('#ajaxGetUserServletResponse').text(responseText);
}
},
});
});
});
</script>
Try this:
Servlet
if(db.loginCheck(userName, password))
{
String greetings = "Success";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
else
{
String greetings = "Invalid Username/Password";
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
Jquery:
$.ajax({
url : 'LoginCheck',
data :datastr,
success : function(responseText) {
if(responseText == "Success"){
windows.location.href='/main.jsp';
}else{
windows.location.href='/error.jsp';
});

how to use jquery ajax in jsp ?

i have written a small code which inclued 2 jsp pages and
1) test2.jsp --> i have made a dropdown in this page
2) test3.jsp --> displays a welcome message when the person selects an option from the dropdown ,
he will migrate to this page without refreshing test2.jsp
for this i have used ajax jquery
when i click on the submit button nothing happens , please help me with this
i have also put the org.json.jar file in the libraries
test2.jsp code
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//malsup.github.com/jquery.form.js"></script>
<script>
function check()
{
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br>
<form method="post" action="test2.jsp">
<select name="city">
<option value="dropdown">select city</option>
<option value="jal">Jalandhar</option>
<option value="ggn">Gurgaon</option>
<option value="noida">Noida</option>
<option value="amrtsr">Amritsar</option>
<option value="bombay">Bombay</option>
</select>
<input type="submit" value="Submit" onclick="check()">
</form>
test3.jsp code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>welcome</h1>
</body>
</html>
The function should return false to prevent form submittion
<script>
function check() {
$.ajax({
url: "test3.jsp",
type: "GET",
success: function() {
alert("succes");
},
error: function() {
alert( "Sorry, there was a problem!" );
}
});
return false;
}
</script>
It should be
<input type="button" value="Submit" onclick="check()">
instead of
<input type="submit" value="Submit" onclick="check()">
because submit input type call form's action that is test2.jsp.
call your javascript function on change event of drop down
onchange="check()"
and navigate through firebug and check your consol it will show you your whole ajax request

how to display Input Vale after clcik On form in jsp

<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>Enter Your Data!</TITLE>
</HEAD>
<script type="text/javascript">
function changeVal()
{
document.getElementById("textfield2").value="abc";
}
</script>
<BODY>
<form method="GET" action='index.jsp' name="good">
<input type="submit" name="submit" value="submit" id="textfield2" />
<input type="text" name="done" value='<%=request.getAttribute("k")%>' />
<% String k=request.getParameter("done");
request.setAttribute("k",k);
%>
</form>
</BODY>
</HTML>
This is my simple index.jsp file code am unable to display text after Button click please Help me how i ll do this after Button click Text disappointing of iN put value
If I understood correct, you want to display submitted value.
Try to change
<input type="text" name="done" value='<%=request.getAttribute("k")%>' />
to
<input type="text" name="done" value='<%=request.getParameter("done")%>' />
But it's better not to do any logic in jsp. Try to move all logic into servlet or any other controller.
You may need to call the changeVal() somewhere in your code, probably in onload of the body.
<script type="text/javascript">
<%
String paramValue = request.getParameter("submit");
paramValue = (paramValue==null)?"":paramValue;
%>
var buttonValue = <%=paramValue%>;
function changeVal()
{
if(buttonValue!="")
{
document.getElementById("textfield2").value = buttonValue;
}
}
function formSubmit()
{
//set the value need to be changed
document.getElementById("textfield2").value="abc";
document.getElementById("good").submit();
}
</script>
<BODY onload="changeVal()">
<form method="GET" action='index.jsp' id="good" name="good">
<input type="button" onclick="formSubmit()" name="submit" value="submit" id="textfield2" />
<input type="text" name="done" value='<%=request.getAttribute("k")%>' />
<%
String k=request.getParameter("done");
request.setAttribute("k",k);
%>
</form>
</BODY>

Categories