Param values not being transferred via AJAX POST request

In my web application using Struts and Velocity, I'm facing an issue where JavaScript needs to pass a parameter to a method in a Java class. I have tried using an AJAX post call to a servlet, but I am not able to receive the parameter in the action class.

JavaScript function:


function postToServlet(){
    var id = 2;
    var param = "Count=" + id;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "DataServlet.action", true);
    xmhttp.setRequestHeader('content-type', 'plain/text');
    xmlhttp.send(param);
}

struts.xml


<action name="DataServlet" method="getFromJS" class="com.test.ServletPost" />

Servletpost.java


public void getFromJS() {
    System.out.println(ServletActionContext.getRequest().getParameter("Count")); // This outputs null instead of "2". Please advise.
}

I'm puzzled as to why the parameters are not being posted properly.

Answer №1

The setRequestHeader method is incorrect:

xmlhttp.setRequestHeader('Content-Type', 'application/json');

The current implementation does not properly set the request headers. This erroneous syntax could potentially result in an error being thrown. Please use the suggested code above, and keep in mind that JavaScript is case-sensitive.

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

Reasons for dividing by 1 in JavaScript

While completing a basic programming assignment from my teacher, I encountered an interesting issue in Javascript. I found that when dividing a number by 1, it returns an unexpected value. Can anyone provide an explanation for this? I have created a jsfidd ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

How can we automatically redirect users to an external website based on their responses to a specific question in SurveyJS?

Within my SurveyJS json, I have a radiogroup question that prompts users to make a choice. If they select a specific option, I'd like to redirect them to a different page. Otherwise, I want them to continue with the survey. Is this achievable? (The s ...

What is the most effective way to integrate webkitSpeechRecognition into a Vue.js project?

I found a demo at this link, but I'm having trouble understanding it. Can you provide a simple implementation? <div id="app"> <v-app id="inspire"> <v-container fluid> <v-layout row wrap justify-cen ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...

The proper way to link various asynchronous operations enclosed in promises

My current understanding of promises is that they serve as a wrapper for async functions within the outer environment (such as the browser or node.js). However, I am struggling with how to properly connect async operations using promises in software develo ...

The datatable fails to render after executing a function in AngularJS

When I load the page without calling a function, the data is displayed in a datatable perfectly fine. However, if I try to generate the datatable after calling a function, it does not work. HTML: <div class="widget-body no-padding"> ...

Understanding the binary format in JavaScript

In my JavaScript project, I am facing a challenge with reading a large table that contains a mix of numbers, enums, and strings. The data is significant in size, so I am exploring the option of converting it to binary format to save space. However, I' ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

The Ajax auto-complete text box feature in ASP.NET is not functioning properly when used within a master page

This code snippet functions properly on a standard asp.net page. However, when used with a master page, it encounters issues. The masterpage.master <asp:TextBox ID="TextBoxSearchCompany" class="form-control" placeholder="Search company..." runat="ser ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...

Trouble with jQuery autocomplete function in Firefox

I've implemented multiple jQuery autocomplete searches similar to this one. While they function properly in Safari, Chrome, and Opera, I'm encountering issues with Firefox. Could it be due to deprecated code usage? The jQuery UI example seems si ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

Utilizing Node.Js for Asynchronous Operations

I have a situation in my code where the Process1() function contains a database loop, causing Process2() and Process3() to be called multiple times. Which function from async should I use to properly wait for a for loop? async.waterfall([ function(ca ...

Calculating collision between circles in Three.js

I've been working on incorporating circle to circle collision for a pool game, aiming to make the balls bounce apart correctly upon impact. Despite trying various tutorials and scouring multiple questions on stackoverflow, I haven't found a solut ...

Are you looking to convert this JSON using underscore or any other JavaScript utility tool?

Looking at this JSON data: [{"target": "mydata.12.2", "datapoints": [[763.7, 1368821100], [762.1, 1368821160], [223.11, 1368821220], [886.54, 1368821280], [112.3, 1368821340]]}] I need to strip the first key and square brackets so it appears like this: ...

What is causing my AJAX function to malfunction and throwing an exception for undefined data objects?

I am having trouble with my ajax query in my code. Even though it is returning the required data, it is not displaying properly within the HTML code. I have a common header and footer (PHP) for all other files. Despite my efforts to resolve this issue by s ...