1

I am working on a pagination code in JSP and Servlet. In this I want to show list of employee's. I try to design this using MVC Pattern.

Steps for invoking following code:

  1. invoke dispEmployee.jsp page in browser.
  2. click on List Hyperlink in it. Which calls EmpServlet.java servlet.
  3. select the page number from select box to navigate from page to page.

Question:

Here When we go as per the steps mentioned above. Up to step2 everything runs fine. when we tries to invoke step3 it i.e when we select another page number from select box it gives information for that selected page but after that whenever we select the other page from select box the change event is not get invoked

Please tell me friend what is wrong in my ajax and jQuery code.

Please refer the following code. Here the DAO and Bean code is not given.

dispEmployee.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Employees</title>
<script type="text/javascript" src="js/stdlib/jquery-1-4-2.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
alert("this is test");
// var link= $('#id_pageselect');
var selpage=$('#id_pageselect').val();
$("#id_pageselect").change(function(){
    alert("this is test1"); 
/*  $.ajax({
     type:"Post",
     url:"/EmpServletSnipet",
     data:"page=" + selpage,
     success:function(content){
                alert("test2"); 
                $('#display').empty();
                $('#display').append(content);
            }
     });*/
     //I have updated code by commenting the $.ajax method.and by writing following lines. 

   //I have also removed the '/' forward slash before EmpServletSnipet in following lines of code. 

    //Its working for fine but only for first chage event of select box after that when

    //I try to change the page from newly rendered select box Its not even invoke change event.

      $('#display').empty;
      $('#display').load('EmpServletSnipet',{page:$("#id_pageselect").val()});       
});
});
</script>

</head>
<body>
<div id="display" style="position:static; left:1003px; top:602px; width:500px; height:600px; z-index:10; overflow: scroll;">
<a href="http://localhost:8080/webdynamic/EmpServlet?page=1">List</a>
<select name="pageselect" id="id_pageselect">
<c:forEach begin="1" end="${noOfPages}" var="i">
            <c:choose>
                <c:when test="${currentPage eq i}">
                    <option value="${i}" selected>${i}</option>
                </c:when>
                <c:otherwise>
                    <option value="${i}">${i}</option>
                </c:otherwise>
            </c:choose>
        </c:forEach>
</select>
    <table border="1" cellpadding="5" cellspacing="5">
<tr>
        <th>Emp ID</th>
        <th>Emp Name</th>
        <th>Salary</th>
        <th>Dept Name</th>
    </tr>
    <c:forEach var="employee" items="${employeeList}">
        <tr>
            <td>${employee.employeeId}</td>
            <td>${employee.employeeName}</td>
            <td>${employee.salary}</td>
            <td>${employee.deptName}</td>
        </tr>
    </c:forEach>
</table>
</div>

The EmpServlet.java servlet acts as controller. This servlet gets page request from jsp file and retrieves employee records from DAO. only doGet and doPost methods are given.

EmpServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int page = 1;
    int recordsPerPage = 5;
    if(request.getParameter("page") != null)
        page = Integer.parseInt(request.getParameter("page"));
    EmployeeDAO dao = new EmployeeDAO();
    List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,
                             recordsPerPage);
    System.out.println("Employee list : "+list.size());
    int noOfRecords = dao.getNoOfRecords();
    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
    request.setAttribute("employeeList", list);
    request.setAttribute("noOfPages", noOfPages);
    request.setAttribute("currentPage", page);
    RequestDispatcher view = request.getRequestDispatcher("displayEmp.jsp");
    view.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request,response);
}

The EmpServletSnipet.java servlet is used to fetch records for selected page on ajax request and send the some code snipet as ajax response which

will be get rendered in a having id as display. only doGet and doPost methods are given.

EmpServletSnipet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("This is EmpServletSnipet");
int page = 1;
    int recordsPerPage = 5;
    if(request.getParameter("page") != null)
    page = Integer.parseInt(request.getParameter("page"));
    EmployeeDAO dao = new EmployeeDAO();
    List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,recordsPerPage);
    System.out.println("Employee list : "+list.size());
    int noOfRecords = dao.getNoOfRecords();
    int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
    PrintWriter pw=response.getWriter();

    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");

    pw.println("<a href=\"http://localhost:8080/webdynamic/EmpServlet?page=1\">List</a>");
    pw.println("<select name=\"pageselect\" id=\"id_pageselect\">");
        for(int i=1;i<=noOfPages;i++){
            if(i==page){
                pw.println("<option value="+ i +" selected>"+ i +"</option>");
            }else{
                pw.println("<option value="+ i +">"+ i +"</option>");
            }
        }

    pw.println("</select>");

    pw.println("<table border=\"1\" cellpadding=\"5\" cellspacing=\"5\">" +
            "<tr>" +
            "<th>Emp ID</th>" +
            "<th>Emp Name</th>" +
            "<th>Salary</th>" +
            "<th>Dept Name</th>" +
            "</tr>");
    Employee emp=null;
    for(int j=0;j<list.size();j++){
        emp=list.get(j);
        pw.println("<tr>" +
                "<td>"+emp.getEmployeeId()+"</td>" +
                "<td>"+emp.getEmployeeName()+"</td>" +
                "<td>"+emp.getSalary()+"</td>" +
                "<td>"+emp.getDeptName()+"</td>" +
                "</tr>");
    }

    pw.println("</table>");
    pw.println("<td><a href=\"EmpServlet?page="+(page-1)+"\" id=\"prevpg\">Previous</a></td>");
    pw.println("<td><a href=\"EmpServlet?page="+(page+1)+"\" id=\"nextpg\">Next</a></td>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request,response);
}

Please guide me in this problem.

Param-Ganak
  • 5,787
  • 17
  • 50
  • 62
  • Your question is not specific enough (it's too much like *"Bam, here's my code. It doesn't work. Please debug it."*). So I am closing as possible duplicate of [How to use Servlets and Ajax?](http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax) and solution 3 of [How to populate child dropdownlists in JSP/Servlet?](http://stackoverflow.com/questions/2263996/populating-child-dropdownlists-in-jsp-servlet) for general answers on how to salvage such a requirement. – BalusC Jan 09 '13 at 12:29
  • @BalusC Sir! I have checked the link that you have given which is help full to me but if you check the jquery code in jsp file when we select the number from combo box it the jquery is get executed till alert("this is test1"); statement but it does not execute the code further. So after solving this issue I will get to know that whether there is any problem in servlet code. So Sir! Please guide me in this. Thank You! – Param-Ganak Jan 09 '13 at 12:40
  • Well, sounds like as if the URL is plain wrong. Just investigate the HTTP traffic to see if the browser didn't actually retrieve a 404 on it. – BalusC Jan 09 '13 at 13:03
  • @BalusC Sir! In above comment of mine I have mentioned that its execute till alert("this is test1"); statement but it does not execute the code further. Now Please refer the jquery code in above jsp code I have commented the old code and added two new lines. I have also mentioned some comment there for ur information. After this change code after the respective alert statement mentioned above will get executed & and returns ajax response but after that when you select again another page in this case it does not event invoke the change event function. Please guide me Sir! – Param-Ganak Jan 10 '13 at 09:58
  • Investigate the HTTP traffic. Is the request sent or not? If so, what did it receive? Press F12 in Chrome/IE9/Firebug and check *Net(work)* tab. – BalusC Jan 10 '13 at 11:52

1 Answers1

0

Try

<script type="text/javascript">
function attach(){
    $('#id_pageselect').on('change',function(){
       $('#display').load('/EmpServletSnipet',{page:$(this).val()});
       // attach again, because the old #id_pageselect is lost!
       attach();
    });
}
$(function(){
    attach();
})
</script>
Grim
  • 1,938
  • 10
  • 56
  • 123