0

I am starting to learn about ajax with jquery and I've tried a lot of googling and I can't get this test code to work can you tell me what am I doing wrong? What happens is that the ajax won't create the table. Here is my code:

The JSP:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="js/jquery.js"></script>
    <title>My First Web App</title>
    <script type="text/javascript">
        $(document).ready(function{
            $.ajax({
                type: "GET",
                url: "users",
                dataType: "xml",
                success: function(xml){
                    $("#content").append("<table>");
                    $(xml).find("user").each(function(){
                        var firstName = $(this).find("firstName").text();
                        var lastName = $(this).find("lastName").text();
                        var password = $(this).find("password").text();
                        var email = $(this).find("email").text();
                        $("#content").append("<tr>");
                        $("#content").append("<td>" + firstName + "</td>");
                        $("#content").append("<td>" + lastName + "</td>");
                        $("#content").append("<td>" + password + "</td>");
                        $("#content").append("<td>" + email + "</td>");
                        $("#content").append("</tr>");
                    });
                    $("#content").append("</table>");
                }
            });
        });
    </script>
</head>
<body>
    <div id="content"></div>
</body>

The servlet:

@WebServlet("/users")
public class users extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public users() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/xml;charset=UTF-8");
    usuarioDAO uDAO = new usuarioDAO();
    response.getWriter().write(uDAO.getAllUsers());
}

usuarioDAO:

public String getAllUsers()
{
    String xml = "";
    xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    xml += "<users>";
    try
    {
        getAllUsers = con.prepareStatement("SELECT * FROM users");
        synchronized(getAllUsers)
        {
            ResultSet res = getAllUsers.executeQuery();
            while (res.next())
            {
                xml += "<user>";
                xml += "<firstName>" + res.getString("firstName") + "</firstName>";
                xml += "<lastName>" + res.getString("lastName") + "</lastName>";
                xml += "<password>" + res.getString("password") + "</password>";
                xml += "<email>" + res.getString("email") + "</email>";
                xml += "</user>";
            }
        }
        getAllUsers.close();
    }
    catch (Exception ex)
    {
        System.out.println(ex);
    }
    xml += "</users>";
    return xml;
}

And that's about it, can you please tell me what am I doing wrong?

hectorviov
  • 77
  • 2
  • 10
  • 5
    Define "doesn't work." In what way does it fail? Is there an error of some kind? An exception? At what point in the code does it deviate from expected behavior? What is the expected vs. observed behavior at that point? What are the states of the relevant objects at that point? – David May 10 '12 at 15:56
  • Are you sure the `url` of your ajax call is correct? – MilkyWayJoe May 10 '12 at 15:56
  • Maybe you forgot to call response.close() or response.flush() here? If it will not help, could you please post some additional details, may be server log or firebug log? – Alexey Ogarkov May 10 '12 at 15:56
  • Sorry @MilkyWayJoe I tried with just the xml alone but it didn't work either. I already edited to the normal URL. – hectorviov May 10 '12 at 16:04
  • @David the way that it doesn't work is that it doesn't show me the table on the JSP, but if I enter the /users it does show me the xml. – hectorviov May 10 '12 at 16:04
  • 1
    @hectorviov: Define "doesn't show me the table." Seriously, you need to be able to debug this. Step through the client-side code with your debugging tool of choice (FireBug, for example), step through the server-side code with your debugging tool of choice (your IDE, perhaps?). The end result of the behavior is not all of the information you have. There's a lot more you can discover. Does the AJAX call reach the server resource? What response does it get from the server? What does the code do with that response? – David May 10 '12 at 16:08
  • Can you add an `alert(xml);` as the first line of your Success function to confirm that you are receiving data from your service? Also, @Matzi is on the right track with his answer below. You are attempting to use the `.append()` function incorrectly. – AndrewR May 10 '12 at 16:56

1 Answers1

0

Same problem as here:

Using .after() to add html closing and open tags

You are trying to add table tag as pure text, but it is not working. Instead of that, add a full table (also tr) tag to the page first, then add additional elements into it. Full elements, not just partials!

UPDATED

Something like this:

                $("#content").append("<table id='table'></table>");
                var i = 0;
                $("#existingElement").html(content);
                $("#existingElement").find("user").each(function(){
                    var firstName = $(this).find("firstName").text();
                    var lastName = $(this).find("lastName").text();
                    var password = $(this).find("password").text();
                    var email = $(this).find("email").text();
                    var rowid = "row"+id;
                    $("#table").append("<tr id='"+rowid+"'></tr>");
                    $("#"+rowid).append("<td>" + firstName + "</td>");
                    $("#"+rowid).append("<td>" + lastName + "</td>");
                    $("#"+rowid).append("<td>" + password + "</td>");
                    $("#"+rowid).append("<td>" + email + "</td>");
                });
Community
  • 1
  • 1
Matzi
  • 13,770
  • 4
  • 33
  • 50
  • If everything else works (the xml is generated) then try the updated code. It seems that find only works in an existing DOM element, not on xml description. http://stackoverflow.com/questions/562283/jquery-find-doesnt-return-data-in-ie-but-does-in-firefox-and-chrome – Matzi May 10 '12 at 18:54