What is the process for transferring a JavaScript variable to a Java servlet?

I am trying to send a JavaScript variable to a Java servlet in a web application I am developing. Below is the HTML code:

<p id="test">Some text</p>

Here is the JavaScript code I am using:

var myVar = document.getElementById('test').innerText;

$.ajax({
    url: 'Test',
    data: {
        myPostVar: myVar
    },
    type: 'POST'
});

Then, in the servlet's doGet method, I have the following code:

String result = request.getParameter("myPostVar");
System.out.print(result);

However, when I test the Test.java file, it returns "null". I have searched extensively online for a solution but have not been able to find one.

Answer №1

The issue at hand is that the ajax call is using the post method while the servlet is expecting a doGet() method.

To resolve this, either change the servlet method to doPost or update the ajax call to use Get instead.

Answer №2

Give this a shot:

void handlePostRequest(HttpServletRequest req, HttpServletResponse res) 
   throws ServletException, IOException
{
    String postVariable = req.getParameter("postVariable");
    // ...
}

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

Getting the parameters of a path from the URL's breadcrumb in Vue.js

Currently utilizing Vue Attempting to include path parameters in breadcrumb URLs for my app's router. Looking to achieve something similar to the following: { path: 'pages/gestion/region/:reg', name: 'gestion-depa', ...

leveraging ajax callbacks, the significance of http status codes and essential validation concepts

Recently, I've been working on a server side AJAX class designed to return a JSON string in response to an AJAX request. One question that has been on my mind is when it would be appropriate to return HTTP status codes based on the server's respo ...

Express in NodeJS: My app contains two app.get requests that seamlessly merge

Need help with distinguishing between two requests in my code: app.get('/assignment/loans', (req, res) => { const idOne = req.query.bookID; } and the other request: app.get('/assignment/loans', (req, res) => { const idTw ...

Utilizing AngularJS in conjunction with Asp: UpdatePanel

<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMasterpage.master" AutoEventWireup="true" CodeBehind="ExamSet.aspx.cs" Inherits="demo.Admin.ExamSet" %> <asp:Content ID="Content1" ContentPlaceHolderID="content" runat="server"> <s ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html: <body ng-app="ysi-app" ng-controller="MainControlle ...

When trying to import the "firebase/app" module, an error occurred stating that the default condition should be the last one to be considered

Greetings! I am diving into the world of webpack and firebase. Every time I use: import { initializeApp } from "firebase/app"; I encounter this error message: https://i.sstatic.net/tvuxZ.png Here is my file structure: https://i.sstatic.net/406o ...

Set provides a value, whereas Get yields null

When the user selects a file path in a file chooser and clicks save, I am trying to save this path using Set & Get. The path is successfully returned to my set method and confirmed with a System.out.println statement. However, when I attempt to use the ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

What is the process for adjusting the expiration time of a GitLab accessToken?

I am currently using NextAuth for logging in with GitLab, but I am encountering an issue where my accessToken changes every 2 hours. How can I ensure that it remains valid for a longer period so that I can successfully store it in my database? It's wo ...

Monitor a nested watch property for potential undefined or default values

Currently tackling an issue in my Vue2 project related to a specific property I'm trying to watch. Here's what the code snippet looks like: watch: { 'car.wheels': function(){ ... } Sometimes, 'wheels' is undefined ...

Identifying sluggish GPU performance on a mobile device using three.js: A guide for developers

My game runs extremely slow on older mobile devices like the Samsung Galaxy S4 and iPhone 5 when shadows are enabled. However, when shadows are turned off, performance improves significantly. Is there a way to detect a slow GPU in order to disable sh ...

Scrolling horizontally using the WinJS list view

In my project, I incorporated a WinJS list view with the display style of ms-flexbox. However, I am facing an issue where the list is scrolling horizontally beyond its width even though I have set overflow to hidden. Is there a way for me to eliminate th ...

Django: Is there a way to modify the PayPal script for pay upon arrival?

I currently do not wish to accept online payments on my e-commerce site. Instead, I would like the courier to handle package delivery and collection of fees. How can I modify the PayPal script to bypass validations and only register payments upon arrival? ...

Assistance with Validating Forms

Hello, I am currently in the process of developing a straightforward registration form that utilizes ajax validation. The form is working as intended for the most part... where an error message displays on the page for each incorrectly filled field. Never ...

Efficient Techniques for Deleting Rows in a Dynamic JavaScript Table

I'm facing an issue where I want to remove each line added by the user, one by one. However, my current program is removing all the rows from the table instead of just one at a time. The objective is to allow the user to remove a specific row if they ...

"Organizing an object array based on a specified order array - a step-by-step

My task involves rearranging objects within an array. Let's assume this is the data array provided: const data = [ { id: 'ETHUVMY0m', name: 'item 1', value: 'value 1' }, { id: 'McfTB40vO', name: 'item ...

What advantages and disadvantages come with using timeouts versus using countdowns in conjunction with an asynchronous content loading call in JavaScript/jQuery?

It seems to me that I may be overcomplicating things with the recursive approach. Wait for 2 seconds before loading the first set of modules: function loadFirstSet() { $('[data-content]:not(.loaded)').each( function() { $(this).load($(thi ...