Encountered problem with AJAX in Java: Unable to assign value to property 'innerHTML' as it is null

Recently, I've been eager to dive into learning AJAX and decided to create an app following a tutorial similar to the one provided here. However, after painstakingly replicating the code, I found that it's not working as expected. Despite multiple efforts to troubleshoot on my own, I'm unable to pinpoint the issue.

This is the content of my .js file:

function ajaxAsyncRequest(reqURL) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", reqURL, true);
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            // How to get message
            alert('It\'s K');
            document.getElementById("message").innerHTML = xmlhttp.responseText;
            alert(xmlhttp.responseText);
        } else {
            alert('Something is wrong !');
        }
    }
};
xmlhttp.send(null);
}

The index .jsp page includes:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="javascript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>
</html>

As for my servlet code snippet:

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;

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("/getTime")
public class GetTimeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
    public GetTimeServlet() {
        super();
    }

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
    public void doGet (HttpServletRequest request,HttpServletResponse response) 
        throws ServletException, IOException 
    {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        PrintWriter out = response.getWriter();
        LocalDate currentTime= LocalDate.now();
        String message = "Currently time is "+currentTime.toString();
        out.write(message);
    }

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

}

Upon clicking the button, I receive an unexpected message at the specified location mentioned in the error line

document.getElementById("message").innerHTML = xmlhttp.responseText;
within the .js file. The application is accessed via http://localhost:8080/HelloAjax/, ruling out any local issues. Given that it loads after the page itself, I remain puzzled about its cause.

Answer №1

The reason document.getElementById("message") is returning null is because there is currently no element with the ID 'message' in the DOM. Consider updating your HTML code as follows:

<body>
    <div id="message"></div>
     <input type="button" value="Get Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>

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

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

Issue with Repeated String Test in JavaScript: Single Failure Detected

Currently tackling the Repeated String Challenge on HackerRank. The challenge description goes as follows: A string, denoted by s, consisting of lowercase English letters is repeated infinitely. With an integer, n, the goal is to determine and output the ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

"NextAuth encounters an issue while trying to fetch the API endpoint: req.body

Trying to implement authentication in my Next.js app using NextAuth.js, I've encountered an issue with the fetching process. Here's the code snippet from the documentation: authorize: async (credentials, req) => { const res = await fetch ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

The Angular 1.x Ajax request is not triggering the expected update in the view

I am encountering an issue with my Angular application where the data retrieved from a JSON file is not updating in the view when the JSON file is updated. It seems like the JSON file and the view are out of sync. As a newcomer to Angular, I am struggling ...

What is the best way to incorporate a token when making an axios ajax request?

Currently in my project I am utilizing Laravel 5.3 along with vue.js 2.0. For my ajax requests, I am using axios (https://github.com/mzabriskie/axios). In order to set the TOKEN, I have followed the documentation provided: <script> axios.defa ...

Notify the entity

When setting an object, I use the following code: n.name = n.name.join(String.fromCharCode(255)); n.description = n.description.join(String.fromCharCode(255)); After setting the object, I try to alert(n); but it only shows [Object] Is there a method to d ...

"Exploring the dynamic capabilities of Node.JS and Java Publisher/Subscriber

I am working on developing an application where communication will be facilitated through a node.js server. This node server is responsible for receiving messages from other peers. Here is the code snippet for my node.js: var zmq = require('zmq&apos ...

Can data be fetched from a local port using either Javascript or ASP.NET?

I have created the code below to broadcast data in a Windows application using C#. UdpClient server = new UdpClient("127.0.0.1", 9050); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); ...

Guide on dynamically assigning the value of an Angular variable to another variable

My website has a slideshow feature with left and right buttons, similar to this example: . I am using Angular to change the image when the left or right button is clicked. In the function, I am incrementing a value: /*SlideShow Pictures*/ $scope.pic ...

Seeking to develop a pair of functions for submitting data via my website's form

I need to pass form data to both Docusign and Zapier with just one button click using JavaScript. When the Submit button is pressed, I want the data to be sent to Zapier without opening a success page and then redirect to the Docusign page with all the in ...

Creating a personalized message for a failed "Get" request using the HTTPS native module in combination with

Currently, I have implemented an Express application that includes an HTTP GET request to an external API. It functions properly when there are no errors; however, I am looking to customize the response sent to the client-side in case of failures: const ht ...

Leveraging npm in vanilla JavaScript applications

Because of limitations set by the governance of my current project, I am unable to utilize many of the modern JS libraries and frameworks. Therefore, for our MVP, we are resorting to using vanilla JS directly loaded to the client (un-minified), which is no ...

How can I delete an item from an array when I click on a selected element using Material React Select Multiple?

I found this helpful CodeSandBox demonstration that walks through how to implement a multiple material select feature. Here is an array containing all the available options: const permissionsGroupList = [ { name: 'Sellers' }, { name: &a ...

The AJAX request fails to trigger following the onbeforeunload event except when the page is manually refreshed

I'm currently working on implementing a solution for handling the onbeforeunload event to display a custom message when the user tries to close the browser tab. I want a prompt like: Are you sure you want to leave this page? (I don't want to use ...

Having trouble configuring the Access-Control-Allow-Origin header to function as originally intended

Despite numerous inquiries on this topic, I'm still unable to resolve my issue. I've been attempting to make a game work with HTML5 in Chrome. You can find the link here. The game is coded using libgdx and I'm sending json data from my app ...

Is there a Java library that can convert XML to JSON without including properties when the input XML contains xsi:nil="true"?

Is there a Java XML to JSON library that can generate JSON output without properties when the input XML has xsi:nil="true"? For example, consider the following XML input: <root> <ele1>Has content</ele2> <ele2 xsi:nil="true" /> ...