Handle Ajax sucess and error in jsp - java

I have Form in JSP which have two input boxes along with submit and clear button like this
<form name="loginForm" method="GET" action="Ajaxexample" id="loginForm">
<table>
<tr>
<td>From Date</td><td><input type="text" name="n1" value=""/></td>
</tr>
<tr>
<td>End Date</td><td><input type="text" name="n2" value=""/></td>
</tr>
<tr></tr>
<tr>
<td><input type="submit" name="validpro_insert" value="Insert"></td>
<td><input type="reset" name="validpro_clear" value="Clear"></td>
</tr>
</table>
</form>
As I have called the servlet using get method in form tag which is used to get data from database via JDBC API and to handle the response I have use ajax like this
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
System.out.println("In get");
PrintWriter out = response.getWriter();
String responseStr = "";
responseStr = addUser(request); // Return either error/success
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(responseStr);
out.print(responseStr);
As I have to write some code to get data from DB in servlet and return that response to ajax which handle success and error on the same jsp like this
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">
var form = $('#loginForm');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
error: function (theRequest,textStatus, errorThrown) {
// Success = false;
alert (theRequest.responseText);
alert(errorThrown);
alert('No graph found');//doesnt goes here
},
success: function (data) {
var result=data;
alert(result);
}
});
return false;
});
</script>
But the problem is that I am not getting any value from servlet in ajax to handle success or error
I think I am facing this problem due to servlet doget() method code.. if there is any other problem plz let me know. Any help should be appreciated

with these changes in my code, it runs successfully
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
String responseSend = "";
String from = request.getParameter("n1");
String to = request.getParameter("n2");
if ((from == null) || (from.equals(""))) {
System.out.println("From null");
responseSend = "error";
}
else if ((to == null) || (to.equals(""))) {
System.out.println("End null");
responseSend = "error";
}
else{
//jdbc code
System.out.println("got it");
int n1 = Integer.parseInt(request.getParameter("n1"));
int n2 = Integer.parseInt(request.getParameter("n2"));
responseSend = "code";
}
out.print(responseSend);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("In get");
processRequest(request, response);
}
As I have added a new method processrequest() with request and response parameters which will return the text/HTML to our Ajax code on the same jsp.Firstly I am confused with success/error in ajax code but now I have found that
error: function (theRequest,textStatus, errorThrown) {
alert (theRequest.responseText);
alert(errorThrown);
},
success: function (data) {
var result=data;
alert(result);
}
The error will be called when it doesn't found servlet at given URL and success will be called when it successfully call the servlet with given type and servlet URL.

I have pasted my code here that work well
Try changing your parameter
Your JSP Page
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>
<form id="form">
Enter Your Name: <input type="text" id="userName" />
</form>
<br>
<br>
<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>
here is your ajax
$(document).ready(function() {
$('#form').submit(function() {
$.ajax({
url : 'GetUserServlet',
data : {
userName : $('#userName').val()
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
}
});
});
});
your servlet file
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName").trim();
if(userName == null || "".equals(userName)){
userName = "Guest";
}
String greetings = "Hello " + userName;
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
}

Related

Dynamically populate a dropdown box with Jquery and Java

Please bear with me as I am new to jQuery, and JEE and am not a programmer :-)
I have followed a number of tutorials on how to dynamically populate a dropdown box; however I can not get it to work.
I want to select a State and populate the Region drop down based on that selection (each State is made up of Regions).
My issue is with the call to the java and return of values.
So far I have (mashed up from a number of tutorials) the following:
HTML
<div class="row">
<div class="col-md-6">
<div class="form-select-group">
<label for="selectState">Select State:</label>
<select class="form-control" id="selectState">
<option value="" disabled selected>Select your State</option>
<option>ACT</option>
<option>NSW</option>
<option>NT</option>
<option>QLD</option>
<option>SA</option>
<option>TAS</option>
<option>VIC</option>
<option>WA</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-select-group">
<label for="selectRegion">Select Region:</label>
<select class="form-control" id="selectRegion">
<option>Please select your State first</option>
</select>
</div>
</div>
</div>
jQUERY
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(response) {
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(response, function (index, value) {
$('#selectRegion').append($('<option>', { value: value.name }, '</option>'));
})
});
});
});
JAVA
package client;
import java.io.IOException;
/**
* The purpose of this View is to return a list of Regions associated with a selected State.
*/
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import server.MySQLConnection;
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
response.getWriter().write("Here " + state);
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
response.getWriter().write("State found");
request.setAttribute("selectRegion", listRegions);
}
}
}
This code answers my question as it allows me to dynamically populate a dropdown box with Jquery and Java:
Java:
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
String json = new Gson().toJson(listRegions);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
JSON:
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(responseJson) {
dataType: "json",
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($("#selectRegion"));
});
});
});
});

Ajax Unique user name search fails JSP

I'm trying to create simple unique username check following this tutorial.
http://javaandj2eetutor.blogspot.com/2013/12/check-username-availability-using-java.html
But My ajax call for username is fails. I'm new to ajax and somewhat new for jsp.
Here is my index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Username Availability</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$(".username").change(function () {
var username = $(this).val();
if (username.length >= 3) {
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "CheckAvalability",
data: "uname="+ username,
success: function (msg) {
$(".status").ajaxComplete(function (event, request, settings) {
$(".status").html(msg);
});
}
});
}
else {
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
<div>
<label class="flable">User Name :</label> <input class="username" type="text" name="username"> <span class="status"></span>
</div>
</body>
</html>
Here is my Servlet
package hsenid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final Logger logger = LogManager.getLogger(CheckAvailability.class);
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
logger.info("Check availability called");
DBConnector dbPool = (DBConnector)getServletContext().getAttribute("DBConnection");
Connection myConn = dbPool.getConn();
String uname = request.getParameter("username");
PreparedStatement ps = myConn.prepareStatement("select username from userdetails where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable</font>");
logger.info("Username detected!!!");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Here is my servlet mapping in web.xml.
<servlet>
<servlet-name>CheckAvailability</servlet-name>
<servlet-class>hsenid.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
This detects if minimum characters aren't added and also gives the massage check availability when type in there so I think jquery is added. Also I've run the servlet in Eclipse Mars. It do check the if a username is in the table or not. So I believe that the problem calling to the servlet because I can't see the log4j console output then. I'm unable find what wrong with my code.
Thanks in advance

How to send data to servlet using ajax without a submitting form

I am new with servlet, I am able to get data from the servlet but not able to send data to it and I want to do this without using a submitting form, can i get some help please
on the click of the button it will go to the servlet and return the text but not the value send to it
This is my index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax
(
{
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){alert(data);},
error:function(){alert('error');}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton" onclick="showHint('GetUserServlet.java', 'travis');">press here</button>
<div id="somediv"></div>
</body>
this my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "Update Sucessful";
String name = request.getParameter("name");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write( name + text); // Write response body.
you could either use $.ajax() or $.post here. since you have used $.ajax(). please refer below correction:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax({
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){
alert(data);
$('#somediv').text(responseText);
},
error:function(){
alert('error');
}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"> </div>
</body>
and your servlet should be:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text = "Update successfull"; //message you will recieve
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println(name + " " + text);
}
You may use $.post method for this purpose.
Here is my solution
index.jsp
<!DOCTYPE html><html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#somebutton").click(function() {
servletCall();
});
});
function servletCall() {
$.post(
"GetUserServlet",
{name : "Message from jsp"}, //meaasge you want to send
function(result) {
$('#somediv').html('Here is your result : <strong>' + result + '</strong>'); //message you want to show
});
};
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
GetUserServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text = "<br>Message from servlet<br>"; //message you will recieve
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println(text + name);
}
}

Print checked values in JSP page

I am trying to print checked values of checkbox list from a JSP page but nothing appears even if some selections are there.
<form action="process" method="POST">
<c:forEach var="item" items="${list.items}">
<input type="checkbox" name="chkSkills" value="${$item.Id}">${item.name}
</c:forEach>
<input type="submit" name="Getvalue" value="Get value" />
</form>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] Answers = request.getParameterValues("chkSkills");
PrintWriter out = response.getWriter();
String ButClicked = request.getParameter("Getvalue");
if (ButClicked != null) {
for (String Answer : Answers) {
out.print(Answer + "<br>");
}
}
//processRequest(request, response);
}
Correct your value attribute to
value="${item.Id}"
Notice, there's no need to put a $ inside the {} again.

Autocompletion using Html tags and servlets

I Am trying to do autocompletion by reading text from a file. its running fine in swings. I want to run it on server. Have used Html tags and servlets its working but when I enter query after pressing enter its showing me matching list
How can I make it autocomplete should I make use of threads or any Html tag for autocompletion. I dont have much understanding of coding. Please help me in this
Here is my servlet code
NewServlet.java
public class NewServlet extends HttpServlet {
public NewServlet() {
}
String json;
ArrayList<String> match = new ArrayList<String>();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// response.setContentType("application/json");
AutoTest1 t = new AutoTest1();
ArrayList<String> words = new ArrayList<>();
Trie suggestions = new Trie();
String fileName = "C:/Users/USER/Documents/NetBeansProjects/HelloWorld/web/WEB-INF/aol.txt";
words = t.readWordsFromFile(fileName);
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
}
suggestions = trie;
try (PrintWriter out = response.getWriter()) {
Gson gson = new Gson();
String prefix = request.getParameter("term");
ArrayList<String> matchingSuggestions = suggestions.getAllPrefixMatches(prefix);
//final List<AutoCompleteData> result = new ArrayList<AutoCompleteData>();
for (String suggestion : matchingSuggestions) {
json = gson.toJson(suggestion);
// result.add(new AutoCompleteData(suggestion,suggestion));
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// response.getWriter().write("<option>"+new Gson().toJson(result)+"<option>"); // Write response body.
response.getWriter().write(json);
}
}
}
autocomplete.jsp
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="js/jquery.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "NewServlet",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
});
</script>
</head>
<body>
<div class="search-container">
<div class="ui-widget">
<input type="text" id="search" name="search" class="search" />
</div>
</div>
</body>
</html>
You can always define a new servlet in web.xml and call that in an AJAX call to return the suggestions.
If your're using jQuery, you can do something like this
main.jsp
<input type="text" list="suggestions" class="inputBox"/>
<datalist id="suggestions">
<option value=" Loading...">
</datalist>
<script>
$(document).ready(function(){
$('.inputBox').on('keyup',function(){
$.ajax({
url : 'yourServletAction'
data : {'query' : $(this).val()}
}).done(function(data,jqXHR){
$('#suggestions').html(data);
});
});
)};
</script>
On Server Side in your doGet(), based on the query parameter, you'll populate the suggestions in an ArrayList and save that as a request attribute like this
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
String prefix =request.getParameter("query");
ArrayList<String> matchingSuggestions = suggestions.getAllPrefixMatches(prefix);
request.setAttribute("suggestions",matchingSuggestions);
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/suggest.jsp");
rd.forward(request,response);
}
Now that the control goes to suggest.jsp, we can use JSTL (download from here) to loop over the list and send the options. In fact you can send JSON back by using Jackson library, but I'm sensing that it's too much to digest at the moment
suggest.jsp
<c:forEach items="${suggestions}" var="suggestion">
<option value="${suggestion}" />
</c:forEach>
This should give you some start :)

Categories