0

I am facing problem while appending the content of a div using ajax.The response from the servlet is printing twice.

Here is the code for both the pages.

demo.jsp

<html>
<head>
    <script>
        function run()
        {
            var content = document.getElementById("output");
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                    content.innerHTML += xhr.responseText;
                }
                xhr.open("POST", "demo", true);
                xhr.send(null);
        }

    </script>
</head>
<body>
    <input type="submit" value="Add Content" onclick="run();"/>
    <div id="output">This is Static Text.</span><br>
    </div>
</body>

DemoServlet

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;

@WebServlet(urlPatterns = {"/demo"})
public class Demo extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("This is Dynamic Text<br>");
        } finally {            
            out.close();
        }
    }
}

The final content of the output div is:

This is Static Text.

This is Dynamic Text.

This is Dynamic Text.

I am unable to understand why the Dynamic Text is printing twice.

Thanks in advance.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Sardeep Lakhera
  • 339
  • 2
  • 13
  • Where exactly did you learn how to use `XMLHttpRequest`? I'd suggest to re-read that resource or look for a better one. – BalusC May 08 '13 at 19:39

1 Answers1

1

I suspect onreadystatechange is being called multiple times, more than one of which is carrying the response. See What do the different readystates in XMLHttpRequest mean, and how can I use them? Put a breakpoint in your handler to check.

You probably want to add a check that the response is complete:

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        content.innerHTML += xhr.responseText;
    }
}
Community
  • 1
  • 1
RichieHindle
  • 244,085
  • 44
  • 340
  • 385