Servlet question: What causes the XMLHttpRequest responseText to consistently appear empty?

I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this:

@WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true)
public class CreateCon extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    ConcurrentHashMap<String, AsyncContext> map;
    public CreateCon() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */

    public void init() {
         map = new ConcurrentHashMap<>();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AsyncContext context = request.startAsync(request,response);
        context.setTimeout(10000);
        if(!map.containsKey("Hello"))
        map.put("Hello", context);
        System.out.print("Inside GET");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AsyncContext context = map.get("Hello");
        PrintWriter writer = context.getResponse().getWriter();
        writer.write(request.getParameter("message"));
        writer.flush();
        System.out.print(request.getParameter("message"));
    }

}

Everything works fine when testing in Eclipse with Tomcat. The code is functioning as expected and I even added a System.out.print to verify the functionality.

However, there seems to be an issue with the following javascript:

function postMessage(){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {

        alert(xmlhttp.responseText);
        }
    }
    xmlhttp.open("POST", "/SampleTest/createcon", true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var messageText = escape(document.getElementById("i1").value);
    document.getElementById("i1").value = "";
    xmlhttp.send("message="+messageText);
}

The onreadystatechange function is triggering as expected, but the xmlhttp.responseText always returns blank.

I'm aware of the same-origin policy, but I'm confused why it's causing an issue here since everything is running on localhost:8080.

Why is this happening and what can I do to fix it?

Answer №1

Finally figured it out! Turns out it was just a simple mistake on my part. I needed to make some adjustments to the startChat() method like so:

function initiateChat() {
    var request = new XMLHttpRequest();
        request.open("GET", "/SampleTest/createcon", true);
        request.send();
        request.onreadystatechange=function(){
            if (request.readyState==4 && request.status==200) {
            alert(request.responseText);
            }
        }
    }

I'm specifically looking for the response from the request initiated by startChat().

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

Choosing multiple images by clicking on their alternative text with jQuery

I am currently working on a project that involves clicking on a thumbnail to enlarge the image and display its name (alt) below it. I have made progress, but there seems to be an issue where only one image is displayed no matter which thumbnail I click on. ...

Verifying email availability using VB.NET WebMethod, JSON, and CustomValidator

I have been researching this issue extensively, both on this site and others, but have yet to find a solution that works for me. My goal is to validate whether a given email address is already in use in a database during the registration process. On my Re ...

What is the process of converting code to JavaScript and React?

There are two methods defined as shown below. const handleClick = React.useMemo(() => !isRunning ? (items: string | string[]) => { if(Array.isArray(items)){ startRun({ items: items }); } else ...

I recently created a "dist" folder through Babel. Is it possible to integrate the files within this folder directly into a fresh React project?

I have a React library that is available on npm. My process for publishing it involves the following steps: To begin, I create a folder called dist using Babel by executing this command- babel ./src -d ./dist Next, I upload the resulting dist directory ...

Invoke jQuery within a nested context once more in the jQuery method sequence

Is it possible to do something like this? jQuery(selector).jQuery(subselector).command(....) Here is the current code snippet: $(' .species') .filter(function () { return !$(this).data('hidden_code_ready'); } .wrapInner('<spa ...

Issue with Enter key not working on an individual textbox within Javascript/PHP chat functionality

Recently, I created a chat feature with text boxes that send messages when the ENTER key is pressed. However, I encountered an issue with it not working for the "Warning" functionality. Whenever I press Enter in this context, nothing happens. Can anyone pr ...

Utilizing JQuery for asynchronous calls with Ajax

I recently started working with ajax calls using jquery and I'm facing an issue while trying to bind values from the Database. The data is returned in a dataset from the Data Access Layer, and I am attempting to bind this dataset to a gridview on my . ...

Error found in event.PreventDefault()

I'm currently implementing Twitter Bootstrap on my application. I added e.preventDefault for the link button within $(document).ready(), but it doesn't seem to be functioning properly. Below is the code snippet: Master page: <a id="lnkLogou ...

Moving a DIV below a fixed-positioned element

I have a website with a scrollable div. It works well, but I also need an absolutely positioned div on top of it - and it still needs to scroll smoothly without any hindrance. You can check out a basic JSFiddle demonstration here: http://jsfiddle.net/41ra ...

Choose a different option when there is a change

Here is an example of JSON data: [{ "user_id": "113", "employe_first_name": "Asaladauangkitamakan", "employe_last_name": "Nasibb" }, { "user_id": "105", "employe_first_name": "Ryan", "employe_last_name": ...

Change the CSS menu item to directly load the website instead of using javascript to replace a placeholder

I have a CSS navigation menu, but I'm facing an issue. When I click on a link in the menu, like Google for example, it only changes the name of the placeholder and doesn't actually load the page. Any suggestions on how to fix this? Thank you for ...

Modifying data on the fly for a Highcharts series

My chart is currently functioning well with data in the options. However, when I leave the data empty for a series and attempt the following code (in order to change the data based on a click event), it fails to work. Any suggestions on how I can rectify ...

Is there a way to save a Morris.js chart as a PDF file

I have successfully created a Morris.js Bar Chart using data from PHP and MySQL. Now, I am looking for a way to export this chart into a PDF format. I have attempted to do so using the FPDF library but I am struggling with the implementation. Can anyone ...

What is the process of integrating Bootstrap into a Node project?

I recently set up a MEAN stack project using npm and am currently including Bootstrap via CDN: link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css') However, I want to add Bootstrap using ...

When it comes to identifying a click outside of an element, the Jquery or Javascript function may encounter some challenges specifically with Internet Explorer

After reviewing various solutions online, I noticed that they all function properly on Chrome and Firefox but encounter issues with Internet Explorer when interacting with an SVG. For instance, consider the following code snippet: $(document).on("click",( ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

JavaScript form with radio buttons

I'm completely new to JavaScript and I'm attempting to create a basic script that will show one form when a radio button is checked, and another form when the second radio button is clicked (with no form displayed when neither is selected). I kno ...

Challenges in using Three.js on mobile devices with orientation capabilities

I'm currently running tests on a web application built using three.js, and it seems that users on tablets, especially Android devices, are experiencing some unusual behavior within the scene. https://i.sstatic.net/FkFi3.jpg Below is how the view sho ...

Converting a JSON object into an array of objects

I am looking to transform the following JSON structure let data = { item1: [11, 12, 13, 14, 15], item2: [16, 17, 18, 19, 20] } into this specific format using JavaScript's native functionalities of arrays or objects (compatible with all web brow ...