Unable to view JSON data outcome in JSP page

Within my .JSP file, I have the following HTML and JavaScript code:

<form id="form">
    <input type="text" name="name" id="name"><br><br>
    <input type="text" name="address" id="address"><br><br>
    <input value="Submit" type="submit" onclick="submitform()">
</form>
<p id="result"></p>
</body>

The corresponding JavaScript function is as follows:

function submitform(){

var  userName = $('#name').val();
var  userAdd = $('#address').val();

var myVar = JSON.stringify({name: userName, address:userAdd});

        $ajax({
            url: 'jsonserverlet',
            type: 'POST',
            data: 'per=' + myVar,
            dataType: 'json',

            success:function(data){

            var json= JSON.stringify(data);
            alert(json + " " + data.name + " " + data.address);
            $("#result").html(data.name + " " + data.address);

            }

        });



};

In addition to this, a new class named User.java was created with relevant data. Subsequently, in the Jsoncontent.java file, within the POST method, variables were set up and a request was made for JSON data like so:

        String jsonData = request.getParameter("per");
        System.out.println(jsonData);

        Gson gson = new Gson();

        User data = gson.fromJson(jsonData, User.class);

        System.out.println("Fetching json object");
        String name = data.getName();
        String address = data.getAddress();

        System.out.println("User Name: "+ name );
        System.out.println("User Address: "+ address );

        User user = new User();

        user.setName(name);
        user.setAddress(address);

        String jsonObj = gson.toJson(user);
        System.out.println(jsonObj);

        out.print(jsonObj); 

Despite the lack of errors or warnings, the issue arises when clicking the submit button as the expected result is not displayed. The reason behind this unexpected behavior remains unclear.

Answer №1

In the context of your previous response, you mentioned that I am seeing a blank browser page with no name or address, suggesting that the browser is moving away from the current page and therefore, there is no Ajax request being made - or more likely, both an Ajax request and a standard HTTP Post request are being sent due to the default submit event not being disabled.

To resolve this issue, you will need to disable the default submit action.

https://api.jquery.com/event.preventdefault/ https://www.w3schools.com/jquery/event_preventdefault.asp

<form id="form">
    <input type="text" name="name" id="name"><br><br>
    <input type="text" name="address" id="address"><br><br>
    <input value="Submit" id="submit" type="submit">
</form>
<p id="result"></p>
</body>


$('#submit').click(function(e){
    e.preventDefault(); //prevent standard post

        $.ajax({
            url: 'jsonserverlet',
            type: 'POST',
            data: $("#form").serialize(),
            dataType: 'json',

            success:function(data){
            var json= JSON.stringify(data);
            alert(json + " " + data.name + " " + data.address);
            $("#result").html(data.name + " " + data.address);
            }
        });
})

Answer №2

Don't overlook the key detail: instead of $ajax, it should be $.ajax

You also have the option to submit the form rather than JSON, like so:

function submitform(){
        $.ajax({
            url: 'jsonserverlet',
            type: 'POST',
            data: $("#form").serialize(),
            dataType: 'json',

            success:function(data){
            var json= JSON.stringify(data);
            alert(json + " " + data.name + " " + data.address);
            $("#result").html(data.name + " " + data.address);
            }
        });
}

In the servlet, retrieve the parameters "name" and "address":

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
    ...
    String name = request.getParameter("name");
    String address = request.getParameter("address");
    ...
}

CHANGES IN ANSWER

I apologize for missing out on the important part of the alert message. Alan Hay's observation is correct, you can use it or switch the type to a button. Regardless, here is the functional code

Servlet.java

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/jsonserverlet")
public class Servlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String jsonData = request.getParameter("per");
        out.print(jsonData);
    }
}

index.jsp

<html>
<head>
        <script src="http://code.jquery.com/jquery-2.2.4.js"
         type="text/javascript"></script>
</head>
<body>
        <form id="form">
            <input type="text" name="name" id="name"><br><br>
            <input type="text" name="address" id="address"><br><br>
            <input value="Submit" type="button" onclick="submitform()">
        </form>
        <p id="result"></p>
</body>
<script>
function submitform(){
var  userName = $('#name').val();
var  userAdd = $('#address').val();

var myVar = JSON.stringify({name: userName, address:userAdd});
        $.ajax({
            url: 'jsonserverlet',
            type: 'POST',
            data: 'per=' + myVar,
            dataType: 'json',

            success:function(data){

            var json= JSON.stringify(data);
            alert(json + " " + data.name + " " + data.address);
            $("#result").html(data.name + " " + data.address);
            }
        });
}
</script>
</html>

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

Conceal the menu in Angular Material when the mouse leaves the button

When the mouse hovers over a button, a menu is displayed on the website's toolbar. The menu is set to close when the mouse leaves a surrounding span element. Now, there is an attempt to also close the menu when the mouse leaves the triggering button i ...

What is the proper way to convert nil to JSON as nil, without representing it as an empty value?

I'm facing an issue in my controller/action where some values turn out to be nil: def my_action @var1 = get_boolean_value || nil @var2 = get_int_value || nil @var3 = get_string_value || nil # there are many more values, any of them might be ...

Exploring the Battery Manager functionality within AngularJS

I am attempting to connect the battery manager object to an Angular controller, but for some reason the controller object does not update when the promise provided by navigator.getBattery() is complete. Below is the code I have written: (function(){ var a ...

Choose the grandparent of an element's parent

Is there a way to select the grandparent element of a child in Javascript without having to chain the .parentElement method twice? Specifically, I am looking for a method that can substitute .parentElement.parentElement when selecting the desired element, ...

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

Can you explain the discrepancy between the two sets of code below?

As I delve into the world of Java and selenium, I am eager to grasp the nuances between the two sets of code provided below. Surprisingly, both codes execute smoothly with identical behavior. WebDriver is an interface that is implemented by the FirefoxDri ...

Efficient Ways to Present and Personalize Indian Date and Time using JavaScript

Hey there, currently creating my website and need some assistance. I'm looking to display the date and time in different sections of the page. Having some trouble with getting Indian time to work properly using PHP. If you could help me out with Ja ...

What could be causing the jQuery effect to not function properly?

After completing a course on Codecademy, I successfully ran the code. However, I prefer to copy and paste the code into my own jquery folder for future reference and practice. The objective of this project was to make the element 'krypton' bounc ...

Can you explain how the Facebook Like button code functions and how I can create a similar feature on my own platform?

I have a website with 250 different items, each containing its own Like button using the standard Facebook "Like" code: div class="fb-like" data-href="http://www.mywebpage.com/myproductpage" data-send="false" data-layout="button_count" data-width="80" dat ...

Angular 2+ enables the creation of dynamic folders and allows for uploading multiple files to the server in a seamless

Can an Angular application be developed similar to FileZilla or Core FTP for uploading files and folders to the server via FTP? I need a way to upload files and folders through the admin panel instead of relying on external applications like FileZilla. ...

The functionality to refresh an input field upon clicking a button is not functioning as expected

I am currently developing a small MVC.NET web application with user input functionality. The goal is to calculate and display the results in two input fields upon button click. However, I am facing an issue where the input fields remain empty after the but ...

Setting up a Collapsing Toolbar specifically for a single Fragment within a Navigation View

The Challenge In my Android app, I have a navigation drawer that contains various fragments. Most of the fragments use a default toolbar, but there is one specific fragment that requires a collapsing toolbar instead. Seeking Assistance How can I dynamic ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

"Exploring the world of JSON with Android and Java

Just delving into the world of JSON and experimenting with the FLOT graph for displaying graphs via WebView. Struggling with JSON parsing to represent my data as JavaScript expects. Despite hours of tinkering, I can't seem to format my JSON output to ...

invoking a function in javascript from react

Currently, I am grappling with the task of invoking a JavaScript function from within React while adapting a "React" based "Menu" onto some existing jQuery functions. Below you can find my code for the menu: class Menus extends React.Component{ co ...

Issue with kendo grid not properly saving recently added data

Unexpected Grid Behavior: Adding a new record Pressing the update button in the grid for the newly added row Cancelling before saving After completing the above actions, the newly added row disappears. View js fiddle example <!DOCTYPE html> <h ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

Sliding in a strange way

Are you experiencing a strange behavior with the slider on your website? When you hover over the image, the caption at the bottom slides up and on mouseout it slides down again. It works perfectly on . However, when navigating to portfolio via the menu on ...

Getting a Java file object that doesn't have a file extension attached

Is there a way to obtain a File instance without prior knowledge of the file extension? I attempted the following code snippet inspired by another solution: String extension = null; String[] myFiles = dir.list(new FilenameFilter() { public boolean acc ...

Is there a way to trigger a JavaScript alert to notify whether a record already exists or not within a PDO MySQL insert query?

I am working with a MySQL database and looking to insert data from a PHP form using PDO connect. Can anyone help me figure out how to display a JavaScript alert popup in the following scenarios: When a record already exists. When a new record has been ad ...