What is the reason behind innerHTML failing to work once a servlet has issued a response?

I need to capture the response from the servlet in the jsp page using JavaScript. I have included the following code:

TestServlet.java:

    package com.test;

    import java.io.IOException;
    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("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        String testString = "Load Check";
        //request.setAttribute("test", testString);
        //request.getRequestDispatcher("").include(request, response);
        response.getWriter().write("Test Success");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Test.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>Test JSP</title>
    </head>
    <body>
    <script type="text/javascript">
      function callServeltAndGetResponse(){
    var servlet = new XMLHttpRequest();
    servlet.onreadystatechange = function(){
        var servletResponse = servlet.responseText;
        document.getElementById("response").innerHTML = servletResponse;
    }
    servlet.open('GET','TestServlet',true);
}

    </script>
    <form onSubmit="javascript:callServletAndGetResponse()">
    <input type=submit>
    </form>
    <div id="response"></div>
    </body>
    </html> 

In the provided jsp page, the content of the div does not change even though the servlet generates a response. What could be causing this issue?

Answer №1

To ensure the page does not reload, it is important to stop the default form submission process.

Consider using this code snippet:

<form onSubmit="javascript:handleFormSubmission(); return false">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to loop through properties of a Typescript interface?

I am currently working with an interface called FilterData, which has the following structure: export interface FilterData { variables?: string[]; processDefinitionKey?: string; } When I make a request to the server, I receive an object named filterS ...

NPM Messer - the innovative chat tool for Facebook Messenger. Ready to see it in action?

Previously, I had the idea of creating my own Messenger client. However, when I reviewed the documentation, it only provided instructions on how to write a chatbot. Despite this obstacle, I stumbled upon something intriguing - a Messer command line client. ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Sending an array of JSON data from PHP to JavaScript

After exploring various solutions on how to get JSON in JavaScript from a PHP array, I am still encountering an error. My myfile.php file includes: <?php ................ print json_encode($data, JSON_NUMERIC_CHECK); mysql_close($con); ?> <html&g ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

The specific characteristics of an item in the programming language Javascript

Imagine having 5 unique buttons on a webpage. Each button, when clicked by the user, triggers a JavaScript function that manipulates the button's state using its individual this.state variable. The challenge lies in creating distinct variables for eac ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

Check for available usernames in real-time using Node.js and Express.js, along with client-side JavaScript

Currently, I am working on a web application using Express, MongoDB, and Handlebars as the templating engine. In this app, there is a form where users can create their unique usernames. I want to implement a feature where a tooltip pops up at intervals to ...

Utilize jQuery to refresh the database with the information retrieved from the ajax-request

I am attempting to update the database. This is what I am doing From my JavaScript code var data = { "jobid": $('#jobid').val(), "names": $('#names').val(), "scripttype": $('#testscripts').val() }; var msg=""; f ...

"An error occurs when trying to trigger a .click() event within a list element

There is a list that can contain either plain text or a link. If there is a link present, the entire list element should be clickable. When attempting to execute the following code: if ($('.link').length) { $('li[data-contains-link]' ...

Encountering a "Unable to use import statement outside a module" issue when trying to import react-hook-mousetrap within a Next.js project

Currently experimenting with Next.js but encountering some challenges. Recently attempted to add react-hook-mousetrap and imported it as per usual: import useMousetrap from "react-hook-mousetrap"; However, this resulted in the following error: S ...

Is it possible to utilize a ternary operator in AngularJS beyond just the class attribute?

Struggling with handling null values while looping through a JSON object using AngularJS. I am still learning the ropes of Angular. <a href="#" data-mycustom="{{product.related}}">...</a> If the 'related' property is null: { " ...

What is the most effective method for utilizing theme colors: utilizing strings, variables, or referencing the theme object?

I recently installed eslint-plugin-sonarjs and it keeps pointing out that I am using the same string - color from palette - repeatedly. It suggests assigning it to a variable for better management. So, what approach do you think is most effective: Should ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

Increase the date by one day excluding weekends (Saturday and Sunday)

My current code is designed to add +1 day to the current date. var date = '30 Apr 2010'; var actual_date = new Date(date); var final_date = new Date(actual_date.getFullYear(), actual_date.getMonth(), actual_date.getDate()+1); Now, I am looking ...

When running JavaScript from a .js.erb file, it gets executed while still being visible as plain text

I'm facing an issue with a form inside a popup window. Here's how it looks: <%= form_tag "/controller/action", :method => :get, :remote => true do %> ... <% end %> Within my controller: respond_to do |format| format.js end ...

PHP does not display the Ajax data from JavaScript

I'm having trouble outputting the elements of an array in PHP that was passed from JavaScript. The JavaScript array seems to be passed correctly, but it's not printing via PHP for some reason. Apologies if my code isn't properly indented. Th ...

When utilizing jQuery version 1.10.2, the HTML markup shows up prior to the page completing its loading process

I am trying to import one HTML page into another, but when I load or refresh the page, the HTML markup appears before the page fully loads. How can I fix this issue? <head> <script type="text/javascript" src="js/jquery-1.10.2.js" ></scr ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Steps for defining a function in AngularJS

I created a function and implemented it in the following manner: JavaScript : function updateInstitution (isValid) { alert('hi'); if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.form.institutio ...