A JSON object received from an AJAX request is either null or empty

I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else facing similar confusion.

My problem involves using a String in Java that originates from client-side JS. While my JS alerts are working correctly, the JSON object in my Servlet appears to be either null or empty. I simply need to pass one string to my servlet in order to execute SQL queries, but I am encountering difficulties in doing so.

Thank you!

HTML File

<div class="jumbotron" id="jumboframe">
    <h1>Enter your URL below</h1>
    <input class="txtUrl" type="text" id="txtUrl" value="...." onfocus="if(this.value == '....') { this.value = ''; }"/>
    <p><a class="btn btn-lg submitButton" href="testpage.html" onclick="getURL()" role="button">Start searching!</a></p>
</div>

<script>
    function getURL() {
        var urlString = document.getElementById("txtUrl").value;
        var params = {url: urlString};

        $.ajax({
            type: "POST",
            url: "testpage.html",
            contentType: "application/json",
            dataType: "text", // "JSON" here doesn't call alerts below
            data: {
                'url': urlString
            },
            success: function(data) {
                alert("did it!");
                alert(JSON.stringify(params));
                alert(JSON.stringify(data));
            }
        });
    }
</script>

Java Servlet

public class JavaServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter out = response.getWriter();
    
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    out.println(builder.toString());
    String url = request.getParameter("url");
    Map<String, String[]> map = request.getParameterMap();  
    out.println(map.toString());  
    out.println(url); 

web.xml

<servlet>
    <servlet-name>JavaServlet</servlet-name>
    <servlet-class>path.to.my.JavaServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>JavaServlet</servlet-name>
    <url-pattern>/testpage.html</url-pattern>
</servlet-mapping>

Once again, thank you.

Answer №1

If you're looking to extract a Json from the request data, make sure to pass it as a String. Your HTML code could resemble the following (I've modified the servlet path to JavaServlet.do).

<div class="jumbotron" id="jumboframe">
            <h1>Enter your URL below</h1>
            <input class="txtUrl" type="text" id="txtUrl" value="...." onfocus="if(this.value == '....') { this.value = ''; }"/>
            <p><a class="btn btn-lg submitButton" href="#" onclick="getURL()" role="button">Start searching!</a></p>
        </div>

        <script>
            function getURL() {
                var urlString = document.getElementById("txtUrl").value;
                var params = {url: urlString};

                var jsonDataStr = JSON.stringify(params); // This will give you the json String
            $.ajax({
                    type: "POST",
                    url: "JavaServlet.do",
                    contentType: "application/json",
                    dataType: "text", // Using "JSON" here won't trigger alerts below * Handle the error thrown by the servlet *
                    data: jsonDataStr,
                    success: function(data) {
                        alert("Your URL is " + data); // **receive the response text**
                        alert("Handle it");
                    },
                    error: function(data) { // Handle any errors
                        alert(data.error().getResponseHeader());
                    }
                });
            }
        </script>

Now, JavaServlet will receive a Json as a String, which needs to be parsed (consider using a third party library like Gson).

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    PrintWriter out = response.getWriter();

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = request.getReader();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line);
    }

    String jsonString = builder.toString(); // obtaining the json from the client
    UrlDto urlDto = new Gson().fromJson(UrlDto.class,jsonString); // parse the json into a Java object
    String yourUrl = urlDto.getUrl();
    out.print(yourUrl); // **Set the response text**
    out.close();        

Remember to set up WEB.XML and define UrlDto:

class UrlDto {
    private String url;
    // Getter and Setter methods ...
}

    <servlet>
        <servlet-name>JavaServlet</servlet-name>
        <servlet-class>servlet.JavaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JavaServlet</servlet-name>
        <url-pattern>/JavaServlet.do</url-pattern>
    </servlet-mapping>

I trust this information proves beneficial.

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

The icons from FontAwesome in Vue do not update when computed

I am seeking a way to dynamically change the header icon based on a conversation property. <a class="navbar-item" :title="$t('header.lock')" @click="makePrivate"> <i class="fas" :class="getLockClass"></i> </a> These ...

What is the best way to store a collection of class instances in a serialized format

Is there a way to convert an object that contains a list of objects into JSON format? Error message received: TypeError: Object of type person is not JSON serializable Here's the code snippet in question: import json class person: def __init__( ...

What is the best way to prevent the chaining of promises and catches in JavaScript?

I am currently developing an API using node and express to create users. However, I find myself struggling with error handling due to the asynchronous nature of MongoDB functions, which makes me feel like I'm trapped in a "promise hell." I anticipate ...

Which API is utilized by duojs for its JavaScript modules?

I am currently utilizing duojs, a front-end web development tool similar to browserify or component. With duojs, you can directly import css and js from the file itself without any external package manifests. While I'm trying to figure out how to wri ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

Is it possible to verify if a user is accessing a webpage through Electron?

If I were interested in creating a basic Electron application that notifies the user upon reaching example.com, is this achievable? If yes, then how can I determine if the user is on a particular webpage? ...

Troubleshooting lpush errors in Node.js with Redis

I'm currently developing a web application using node.js and redis. The goal is to store each incoming request in a redis queue before saving it into a database. However, I keep encountering an error whenever the program executes the lpush command. Be ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

Efficiently loading components in Angular using browserify with lazy loading

As I work on developing the architecture of a complex application with Angular, I have started with the angular-seed project which seems to be a solid starting point. However, one issue that concerns me is how Angular apps tend to load everything upfront b ...

Create a JSON file with UTF-8 encoding

I'm currently developing a function that writes JSON data to a file, and everything seems to be working well. However, despite specifying the output as UTF-8, Oxygen is having trouble reading pound and euro signs. Here's the Java code snippet: ...

When trying to import axios from the 'axios.js' file in the 'lib' directory, a SyntaxError was encountered with the message: Unexpected identifier

My server.ts is causing issues. What am I doing wrong? const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const morgan = require('morgan'); const axios = requ ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

Ways to retrieve a specific item from a constantly changing knockout observableArray without employing a foreach loop

Why can I only access one property ('member_A') of an Element in an observableArray using an HTML <input>? I am attempting to add a new object of type abc() to the observableArray "list_of_abc" when the button "ADD To List of abc" is click ...

Conflict arising from duplicated directive names in AngularJS

Hey there, I've got a question for the experts. How can I prevent conflicts with directive names when using external modules? Right now, I'm utilizing the angular bootstrap module, but I also downloaded another module specifically for its carouse ...

Instructions on inserting a new row beneath a selected row using jQuery

https://i.stack.imgur.com/AlwHm.png When the second column is clicked, the method below is called: function getListOfList(primaryId, isFlat, col) { alert(primaryId) $.ajax({ url : ("/" + serverURL + "/dataGrid/getChilds"), ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Is it possible to use a JavaScript string as a selector in jQuery?

So, my issue is with the following JavaScript code snippet: for ( i=0; i < parseInt(ids); i++){ var vst = '#'+String(img_arr[i]); var dst = '#'+String(div_arr[i]); } I'm wondering how I can proceed in jQuery to handle ...

Python encountered a ValueError due to an embedded null character while trying to Import a JSON file

I'm encountering an issue while attempting to import a JSON file into Python. with open('e:\0_1export.json', 'r') as f: data = f.read().strip(); Error message: ValueError Traceback (most rece ...

Is it possible to dynamically change the port for an Express server?

Here is a common question that often arises among beginners, as I had the same query when I first started Is there a way to set the port for express without manually coding it or selecting a port yourself? This was something that puzzled me during my init ...

Can you explain the difference between the <li> and <div> elements in HTML? How are they used differently

I'm currently exploring the elements for Selenium usage. I have a question about the <li> tag in HTML - could you explain its significance to me? Also, how does it differ from the <div> tag? ...