title: Ajax response from a servlet is printing twice
body: <p>I am facing problem while appending the content of a <strong>div</strong> using ajax.The response from the servlet is printing twice.</p>
  
  <p>Here is the code for both the pages.</p>
  
  <p><strong>demo.jsp</strong></p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
      &lt;script&gt;
          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);
          }
  
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;input type="submit" value="Add Content" onclick="run();"/&gt;
      &lt;div id="output"&gt;This is Static Text.&lt;/span&gt;&lt;br&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>DemoServlet</strong></p>
  
  <pre><code>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&lt;br&gt;");
          } finally {            
              out.close();
          }
      }
  }
  </code></pre>
  
  <p>The final content of the <strong>output</strong> div is:</p>
  
  <p>This is Static Text.</p>
  
  <p>This is Dynamic Text.</p>
  
  <p>This is Dynamic Text.</p>
  
  <p>I am unable to understand why the Dynamic Text is printing twice.</p>
  
  <p>Thanks in advance.</p>