Issues encountered when attempting to send a JSON object from Javascript to a Servlet using AJAX

I've been attempting to send a JSON object to a servlet using AJAX, but I'm running into an issue where the object is showing up as null in the servlet. Can't seem to pinpoint the problem in this code.

JAVASCRIPT

function submitValues(event, val1, val2) 
{    
var xmlHttpObj = new XMLHttpRequest();                
            if(window.XMLHttpRequest) 
            {
                xmlHttpObj = new XMLHttpRequest();                    
             }
            else if(window.ActiveXObject)
            {
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");

            }


     var jsonObject =  submitTheValues(event, val1, val2);
       alert("json is:" +jsonObject);
     var json = JSON.stringify(jsonObject);
       alert("json after stringify:" +json);

        xmlHttpObj.open("POST", "../myapp/myservlet", true);
        xmlHttpObj.setRequestHeader("Content-type", "application/json");                    
        xmlHttpObj.send(json);

}  

SERVLET

String jsonObj = request.getParameter("json");

Answer №1

In order to receive the data as a parameter, you will need to send it using the application/x-www-form-urlencode format.

xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");                    
xmlHttpObj.send('json='+encodeURIComponent(json));

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

Refreshing ApolloClient headers following a successful Firebase authentication

I am encountering an issue while trying to send an authorization header with a graphql request when a user signs up using my React app. Here is the flow: User signs up with Firebase, and the React app receives an id token. User is then redirected to ...

Is there a way to connect either of two distinct values in Angular?

Looking to assign the data with two possible values, depending on its existence. For instance, if I have a collection of TVs and I want to save the "name" value of myTVs[0] and myTVs[1]. For example: var myTVs = [ { "JapaneseTV": { ...

Secure Socket Layer (SSL) combined with Asynchronous

Specifics include Apache2, Tomcat6, jdk1.6, struts2, Ajax, and jQuery. My inquiry is: A website that functions flawlessly on Http mode (Apache2 HTTP + Tomcat + Struts2) is facing issues when attempting to work in Https (Apache2 HTTPS + Tomcat + Struts2) ...

Is it beneficial to create two distinct node applications—one to serve a webservice and another to consume that webservice in order to display it on a browser?

Is it more efficient to run two separate node instances for different purposes (webservice engine/data engine and webservice consumer), or is it better to combine both functions in the same application? ...

PHP script integration with WHMCS

I've been attempting to add analytic.php into head.tpl in WHMCS, but I keep encountering an error. Analytic.php location: root/analytic.php Head.tpl location: root/whmcs/template/six/includes/head.tpl I read that WHMCS supports Smarty PHP, so I&apos ...

When the page loads, the HTML side menu will automatically scroll to the active item in a vertical

My website features a vertical side menu with approximately 20 items. The issue I am facing is that when a user clicks on an item, the destination loads but the side menu must be manually scrolled to find the active item if it's located at the bottom ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

Discover how to initiate an ajax request from a tailored module when the page is loaded in ActiveCollab

When trying to initiate an AJAX call on the project brief page by adding a JavaScript file, I encountered some issues. My goal is to display additional information along with the existing project brief. I included a JavaScript file in a custom module and f ...

How to fetch a list of users in an organization from Azure DevOps using Python API call

I'm attempting to create a basic api call in Python to Azure DevOps to retrieve a list of users. The URL is returning results when accessed through a browser, but I am encountering an error while scripting it as shown below. I need assistance in prope ...

Is there a way to direct to a particular section of an external website without relying on an id attribute in the anchor tag?

I am aware that you can link to specific id attributes by using the following code: <a href="http://www.external-website.com/page#some-id">Link</a> However, what if the external HTML document does not have any ids to target? It seems odd tha ...

Using Special Characters in React JS Applications

When handling CSV uploads with accented characters such as émily or ástha, I encountered the need to encode and pass them to the backend. Experimenting with different approaches, I tried adjusting the file type in FormData from 'text/plain' to ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...

What is the most effective way to utilize an existing table in MySQL with a TypeORM entity?

While working with typeorm to connect to a mysql db, I encountered an issue where my table definition was overwriting an existing table in the database. Is there a way for me to use the entity module to fully inherit from an existing table without causin ...

Is there a way to protect the privacy of State variables within a Flux Store?

Currently, I've implemented my own version of the Flux pattern in a small scale in order to deepen my understanding of the concept. So far, it's been working well and I've been gaining valuable insights! However, I've encountered a chal ...

Retrieving JSON formatted spreadsheet information using axios in combination with Vue.js

I am attempting to retrieve rows/data from a Google Sheet in JSON format. <script> const url = "https://spreadsheets.google.com/feeds/list/1NXF6G5npwcGeo2v_9tSDzieSHjxe4QtA-I9iPzHyvMk/1/public/values?alt=json"; const axios = require(" ...

<f:ajax> Executing Java method multiple times - how can it be triggered just once?

Utilizing ajax, I invoke the java method bean.findDetail(). When this method successfully retrieves the detailItem object from the database, the remaining inputTexts are displayed. <h:inputText id="worker" value="#{bean.item.id}"> <f:ajax event= ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...

What could be causing the missing key value pairs in my JSON parsing process?

I have set up a Rails backend to serve JSON data, such as the example below from 2.json: {"id":2,"name":"Magic","location":"Cyberjaya","surprise_type":"Great","instructions":"test","status":"awesome","pricing_level":3,"longitude":"2.90873","latitude":"101 ...

Exploring the power of AngularJS with ng-click functionality and utilizing services

As a beginner in AngularJS, I am facing a knowledge gap when it comes to integrating a barcode scan feature into my application. What I want to achieve is quite simple - a button in the view that, when clicked, triggers a barcode scan. Once the scan is com ...

A guide to saving an ArrayBuffer as a file using JavaScript

I am currently developing a file uploader for the Meteor framework. The approach involves breaking down the file on the client side from an ArrayBuffer into small packets of 4096 bits, which are then sent to the server through a Meteor.method. The abridge ...