0

I have a CRUD table that lists a bunch of products, what I need is that when I click on a button, Ajax automatically sends a request to the servlet telling it that I want to change the state (instead of deleting the product) in the database, then after that is done it should reload the table.

I already have most of the code done, here is the AJAX that I had (Which I suppose is the part that is wrong), I was working on it trying to get it to work when I clicked on a row so ignore that part, there's a delete button per row).

       <script>
                        $("#test").on('click','tr',function() {
                            var id = $(this).find("td:first-child").text();
                            console.log(id);
                            $.ajax({
                            url: "statecontroller.do",
                            type: 'POST',
                            data: { id : id},
                            success: function() {
                            }
                          });
                        });
    </script> 

And here is the servlet code:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));  
            ProductDAO productBD = new ProductDAO();
            Product products = productBD.selectById(id);
            if(products.getState() == "Active"){
                    Product product = new Product(id,"Not Active");
                    productBD.update(product);
                    ArrayList<Product> productList = new ArrayList<>();
                    productList = productBD.selectAll();
                    request.getSession().setAttribute("productList", productList);
                    request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
                }else if(products.getState() == "Not Active"){
                    Product product = new Product(id,"Active");
                    productBD.update(product);
                    ArrayList<Product> productList = new ArrayList<>();
                    productList = productBD.selectAll();
                    request.getSession().setAttribute("productList", productList);
                    request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
                }

}

I tried looking it up but only found how to do this with Spring

(Here is the full servlet code, it has Spanish names on it which is why I translated it for the original post):

package controladores;

import daos.ClienteDAO;
import dtos.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author lycan
 */
@WebServlet(name = "ControladorEstado", urlPatterns = {"/controladorestado.do"})
public class ControladorEstado extends HttpServlet {

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            int id = Integer.parseInt(request.getParameter("id"));  
            ClienteDAO clientebd = new ClienteDAO();
            Cliente clientes = clientebd.selectById(id);
            if(clientes.getEstado() == "Activo"){
                    Cliente cliente = new Cliente(id,"No Activo");
                    clientebd.update(cliente);
                    ArrayList<Cliente> lista = new ArrayList<>();
                        lista = clientebd.selectAll();
                        request.getSession().setAttribute("lista", lista);
                        request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
                }else if(clientes.getEstado() == "No Activo"){
                    Cliente cliente = new Cliente(id,"Activo");
                    clientebd.update(cliente);
                    ArrayList<Cliente> lista = new ArrayList<>();
                        lista = clientebd.selectAll();
                        request.getSession().setAttribute("lista", lista);
                        request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
                }

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

And here is the listing code:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- 
    Document   : listar
    Created on : 19-oct-2018, 11:00:29
    Author     : lycan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <%@include  file="../WEB-INF/jspf/estilos.jspf"%>
        <title>Sistema Ventas</title>
    </head>
    <body>
        <div class="container-fluid">
            <%@include  file="../WEB-INF/jspf/header.jspf"%>
            <%@include  file="../WEB-INF/jspf/nav.jspf"%>
            <section>
                <table id="test" class="table table-bordered">
                    <thead class="thead-dark">
                        <tr>
                            <th>ID</th>
                            <th>Nombre</th>
                            <th>Descripcion</th>
                            <th>Categoria</th>
                            <th>Estado</th>
                            <th><i class="fas fa-binoculars"></i></th>
                            <th><i class="fas fa-pen-alt"></i></th>
                            <th><i class="fas fa-user-times"></i></th>
                        </tr>
                    </thead>
                    <tbody>
                    <c:forEach var="clientes" items="${sessionScope.lista}">
                     <tr>
                            <td>${clientes.id}</td>
                            <td>${clientes.nombre}</td>
                            <td>${clientes.descripcion}</td>
                            <td>${clientes.categoria}</td>
                            <td>${clientes.estado}</td>
                            <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
                            <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
                            <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
                        </tr>
                    </c:forEach>  

                    </tbody>
                </table>
            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=crear" class="btn btn-primary btn-lg " role="button">Registrar</a>
            <a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=buscar" class="btn btn-primary btn-lg " role="button">Buscar</a>    
            </section>   
            <%@include  file="../WEB-INF/jspf/footer.jspf"%> 
        </div>        
        <%@include  file="../WEB-INF/jspf/js.jspf"%>
        <script>
                            $("#test").on('click','tr',function() {
                                var id = $(this).find("td:first-child").text();
                                console.log(id);
                                $.ajax({
                                url: "controladorestado.do",
                                type: 'POST',
                                data: { id : id},
                                success: function() {
                                }
                              });
                                 // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                            });
        </script> 
    </body>
</html>
Darkly
  • 385
  • 1
  • 3
  • 18

1 Answers1

0

okay i see what you are doing now, thanks for including more information. The reason why nothing happens is because in your servlet you are trying to return the same page you are making the ajax call from. (and you're not even handling the response)

From the looks of it, you want to return a table through the ajax method, but in order to do that you need to create a separate jsp that you will return.. For example:

create a new jsp called user-table inside /wcliente/

user-table.jsp

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
       <table class="table table-bordered">
                <thead class="thead-dark">
                    <tr>
                        <th>ID</th>
                        <th>Nombre</th>
                        <th>Descripcion</th>
                        <th>Categoria</th>
                        <th>Estado</th>
                        <th><i class="fas fa-binoculars"></i></th>
                        <th><i class="fas fa-pen-alt"></i></th>
                        <th><i class="fas fa-user-times"></i></th>
                    </tr>
                </thead>
                <tbody>
                <c:forEach var="clientes" items="${lista}">
                 <tr>
                        <td>${clientes.id}</td>
                        <td>${clientes.nombre}</td>
                        <td>${clientes.descripcion}</td>
                        <td>${clientes.categoria}</td>
                        <td>${clientes.estado}</td>
                        <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
                        <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
                        <td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
                    </tr>
                </c:forEach>  

                </tbody>
            </table>
</data>

Now in your servlet, instead of this:

request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);

do this:

request.getRequestDispatcher("/wcliente/user-table.jsp").forward(request, response);

For the ajax in your listar.jsp do this instead:

<script>

$("#test").on('click','tr',function() {  
 var id = $(this).find("td:first-child").text();

    $.post("controladorestado.do", {id : id}, function(responseXml) {                // Execute Ajax POST request on URL of "controladorestado.do" and execute the following function with Ajax response XML...
        $("#test").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "test".
    });
});

 </script>

Reference: How to use Servlets and Ajax?

Jonathan Laliberte
  • 2,672
  • 4
  • 19
  • 44