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

What could be causing the context of 'this' in Javascript to remain unchanged in this particular scenario?

Currently, I am exploring the concept of 'this' in Javascript and have encountered a perplexing situation. After delving into how JavaScript functions operate as outlined here, I grasped that when a function is invoked on an object, the object i ...

Utilizing Angular.JS to sort items based on the chosen option in a select dropdown menu

I am utilizing the WP API to display a list of posts on a page from a JSON file. I have successfully implemented filtering through an input field named searchrecipe, which allows me to search for post titles. However, I am facing a challenge with filterin ...

Struggling with configuring the DEFAULT_VIEW_INCLUSION setting for Jackson views

If you're looking for more information on Jackson views, check out the official documentation available at . According to the docs, you should use the following line of code to exclude properties that are not explicitly mapped to a view: objectMapp ...

Rendering JSON responses in React.js can be achieved using either the fetch function or axios library

I've spent way too much time struggling and I can't seem to concentrate anymore. My goal is simple - I just want to fetch JSON data from a URL and display it visually in the browser. It doesn't even have to be formatted, at least not until ...

`How to efficiently handle intricate JSON data structures in Haskell`

Currently, I am working on building a JSON parser in Haskell. Initially, I successfully parsed a single object using the guide available at . However, I have encountered a challenge when trying to parse the complex data structure below. This data consist ...

Sending an ajax request to submit the results of jQuery.each loop

$(".submitinfo").each(function() { // Using ID as POST name and value as POST value }); // Sending the data using ajax request $.ajax({ url: 'submit.php', traditional: true, data: { 'submit':'true', 'age&a ...

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Sorting a set of 5 items efficiently with just 7 comparisons

I am intrigued by the challenge of sorting 5 items using only 7 comparisons. Although I understand the theory behind it, I am struggling to translate it into code. I came across an example in LISP which did not seem to work for me Despite my efforts, I co ...

Detecting the existence of a scrollbar within the document object model using JavaScript - a guide

Could someone provide a JavaScript syntax for detecting the presence of a scrollbar in the DOM by measuring the body height and window height? ...

Is there a way to expand jQuery quicksearch functionality to include searching for words with accents?

Hello everyone, I'm currently working on the development of this website using jQuery isotope, WordPress, and jQuery quicksearch. Everything is functioning perfectly, but I would like to enhance its functionality. For example, when I type "Mexico," I ...

JavaScript: What's the best way to update the URL in the address bar without triggering a page refresh?

Similar Question: How can I use JavaScript to update the browser URL without reloading the page? I've observed websites like GMail and GrooveShark altering the URL in the address bar without having to refresh the entire page. Based on my understa ...

Steps for enabling a feature flag via API in specific environments

Within my project, I am working with three separate environments and I am looking to activate a feature flag only for a specific environment. Is it feasible to toggle an unleash feature flag using the API for just the development environment? The code snip ...

Error encountered while trying to retrieve Instagram JSON data via request due to an abrupt end of input

I am attempting to retrieve the JSON data from Instagram's URL: . When I enter this URL in my browser, it displays the JSON information. However, I want to be able to access this data using Express so that I can extract any necessary information. co ...

What is the best way to transfer boost::log::expressions::smessage to the nlohmann::json constructor?

I am working with a code snippet that resembles the following: const auto jsonFormatter = boost::log::expressions::stream << boost::log::expressions::smessage; My goal is to encode the message using nlohmann::json, like this: nlohmann::json json ...

Modify form layout upon selection of a specific radio button

Hey there! I'm a student currently diving into the world of JavaScript, CSS, and HTML. However, I've encountered a little problem while working on an exercise that involves using Bootstrap. function ShowForm(formId){ document.getElementByI ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

Determine the total amount of words within a given text

Currently working with Java and Selenium, I am facing an issue where I am trying to extract the number of words from a specific text. However, my results are exceeding my expectations. The HTML structure I am dealing with is as follows: <div data-v ...

Using JQuery and Ajax, what is the best way to transfer information from a popup form to a PHP page?

I've noticed that my question has been asked a few times already, but I'm still struggling to get my code working. It seems like I'm using the same code as those solutions, so I can't figure out what's going wrong. Currently, I am ...

What steps can be taken to ensure that AngularJS does not detach a form input's value from its model if it is invalid?

While working on a form implementation in AngularJS, I encountered a baffling behavior that has left me puzzled. It seems that whenever I set ng-minlength=5 as an input attribute, AngularJS disconnects the value until it meets the length requirement. Thi ...

Is there a way to automatically execute this function when the React component is loaded, without the need for a button click?

After spending a few days trying to figure this out, I'm hitting a wall. This ReactJS project is new for me as I usually work with C#. The goal is to create a print label component that triggers the print dialog when a link in the menu is clicked. Cu ...