AJAX - No envia el formulario por medio de AJAX

 
Vista:
Imágen de perfil de Luis Enrique

No envia el formulario por medio de AJAX

Publicado por Luis Enrique (2 intervenciones) el 16/10/2015 17:34:05
Hola amigos, sucede que yo quiero enviar datos de un formulario JSP a un Servlet por medio de AJAX (JQuery), estoy usando un metodo que hace que no se recargue la pagina con:

1
2
3
$.ajax({
     url, type, data
});

Este metodo....pero cuando pruebo mi pagina me manda puros valores nulos, es decir, cadenas vacias. Me podrian ayudar porfa.

Este es el formulario "RegistrarArea.jsp":

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<%@page import="modelo.Usuario"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.ResultSet" %>
<%@page import="modelo.database" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
        <script type="text/javascript" src="js/areas.js"></script>
        <link rel="stylesheet" type="text/css" href="css/estilos-capas.css" />
        <title>Registro Areas</title>
    </head>
    <body>
        <div style="float: left; margin-left: 60px; margin-top: 40px;" >
            <form  id="frmRegArea" >
                <table>
                    <tr>
                        <td>Nombre de Area:</td>
                        <td><input type="text" id="txtarea" placeholder="" ></td>
 
                    </tr>
                    <tr>
                        <td>Encargado:</td>
                        <td>
                            <select id="cmbencargado">
                                <option value="0">--------------------</option>
                                <%
                                    int contador=1;
                                    ResultSet rs= Usuario.ConsultarUsuario();
                                    try{
                                        while(rs.next()){
                                            out.println("<option value='"+contador+"' >"+rs.getString(1)+"</option>");
                                            contador++;
                                        }
                                    }catch(Exception ex){
                                        ex.printStackTrace();
 
                                    }
                                %>
                            </select>
                        </td>
                    </tr>
                </table>
            </form>
                <br><button id="btRegArea" type="submit" >Enviar</button>
        </div>
    </body>
</html>

Este es mi servlet a este le envio el formulario "ServletRegistrarArea" :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package controlador;
 
import java.io.IOException;
import java.io.PrintWriter;
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 modelo.Area;
import vista.BeanArea;
 
/**
 *
 * @author Kunio
 */
@WebServlet(name = "ServletRegistrarArea", urlPatterns = {"/ServletRegistrarArea"})
public class ServletRegistrarArea 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 {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            String area= request.getParameter("txtarea");
            String encargado= request.getParameter("cmbencargado");
 
           // if(!area.equalsIgnoreCase("") && !encargado.equalsIgnoreCase("")){
             //   BeanArea Barea= new BeanArea(area, 0, encargado);
               // String mensaje= Area.RegistrarArea(Barea);
                //out.println(mensaje);
            //}else{
 
                out.println(area+" "+encargado); ///Aqui estoy imprimiendo lo que recibe del JSP
 
           // }
        }
    }
 
    // <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>
 
}

Y este es mi archivo JavaScript "areas.js" :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$(document).on("click","#btRegArea",function(evento){
 
    var datos= $("#frmRegArea").serialize();
 
    $.ajax({
        type: 'POST',
        url: "ServletRegistrarArea",
        error:function(data){
 
            $("#resultado").html("Error al procesar los datos del Formulario: "+data);
        },
        data: datos,
 
        success: function (data) {
            if(data=== 1){
                $("#resultado").html("");
                $("#div-oculto").fadeOut();
                alert("Correcto: "+data);
            }else{
                alert("Error: "+data);
            }
        }
    });
});
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder