What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet.

$.ajax({                    
    url: 'myServlet?action=FEP',
    type: 'post',
    data: {machine: i, name: txt}, // where i and txt hold certain values
    success: function (data) {
        alert('success');
    }
});

In my Servlet code:

String jspAction = request.getParameter("action");

//...

if(jspAction.equals("FEP")){
    int idMachine = Integer.parseInt(request.getParameter("machine")); 
    String name = request.getParameter("name");
    double value = actions.getValue(idMachine, name); //<-- the value I want to send back to the JSP.
}

The data is sent successfully. However, I am currently unsure of how to return the value back to the JSP page.

Answer №1

To send a string in response, the code snippet would be as shown below:

response.getWriter().write("Sample String Response");
return null;

If you prefer returning JSON data, there are various libraries available such as: http://www.json.org/

You can achieve this by implementing the following code:

response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
int anInt = 42;
jsonObject.put("result", anInt);
response.getWriter().write(jsonObject.toString());
return null;

Answer №2

To utilize the code snippet below to output a value:

response.getWriter().write(value);
 return null;

In your ajax success function, you can access the returned value. For more in-depth explanation, check out the link provided

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

Having trouble displaying images using ejs.renderfile

I've been struggling to generate a PDF from an EJS file with the image rendering correctly. Here is my setup: My app.js code snippet: let express = require("express"); let app = express(); let ejs = require("ejs"); let pdf = require("html-pdf"); let ...

Issue with React Native TextInput failing to update state within a functional component when onChange event is triggered

When using a TextInput in a React Native functional component, I am facing an issue where the state for "name" is not updating properly when onChange occurs. To debug this issue, I have added a console log in useEffect to monitor the new state value. Howe ...

Error: Reference 'ref' is undefined in the 'no-undef' context. I am interested in experimenting with loading images from Firebase storage

While working with React, I encountered an issue when trying to fetch an image URL from Firebase Storage and display the image. The error 'ref' is not defined (no-undef) occurred. https://firebase.google.com/docs/storage/web/create-reference Th ...

Injecting a component in Angular 2 using an HTML selector

When I tried to access a component created using a selector within some HTML, I misunderstood the hierarchical provider creation process. I thought providers would look for an existing instance and provide that when injected into another component. In my ...

Return the information from Node.js to the JavaScript on the client side

My goal is to establish a fetch connection from client-side JS to the server Node.JS. When a person clicks on a button in HTML, it triggers a search in the MongoDB database on the server side. Once the element is found, I am unsure how to send that informa ...

Resizing Bootstrap Modal using React with a Personalized Dimension

Is there a way to manually set the width of Bootstrap's Modal React component on my website? I want to be able to define the width in pixels, and if possible, use a const object in the .jsx file for CSS. If not, I can resort to using a .css file. Be ...

Resolving the Enigma: Querying jQuery for Real-Time Validation and

I'm fairly new to jQuery and I'm facing a challenge in my registration form script. Specifically, I want to check if the entered username or email is already taken while the user is typing. Currently, this functionality works by making a json req ...

Animating jQuery Accordion in Horizontal Direction Extending to the Far Right

After implementing a horizontal accordion in jQuery based on the tutorial found at the following link: A minor issue arose during animation where a slight space was added on the far right side, causing the tabs to shift slightly. This problem is particula ...

Is it possible to automatically submit a form at regular intervals without reloading the page and simultaneously insert the submitted data into

I am attempting to automatically submit a form every x number of seconds without refreshing the page and then insert the input data into a MYSQL database. The problem I'm facing is that while I can successfully insert the form's input value into ...

Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS: body { counter-reset: h1; } h1 { counter-reset: h2; } h2 { counter-reset: h3; } ... T ...

Having trouble aligning material-ui GridList in the center

I am currently working with a GridList in order to display Cards. The styling for these components is set up as shown below: card.js const useStyles = makeStyles({ card: { maxWidth: 240, margin: 10 }, media: { heigh ...

Utilize PHP in an APP Engine Application to send an email to a Gmail address

I have a project deployed on Google App Engine where I need to send an email once a user submits the contact form. My app is successfully deployed and I have implemented an ajax request to a PHP file, but unfortunately, it's not functioning as expect ...

The debugger successfully displayed the HTML page in the POST response, but it was not visible in the browser when

Having an issue with my connection form that is sending a Post request to a servlet. The servlet then forwards the request to different pages after performing some tests such as password and email verification of the user. However, the problem I am facing ...

Using Rails to Execute a js.erb File with an AJAX Request

When using JavaScript, I make a call to a controller through AJAX in the following way: $.ajax({ type: 'GET', url: '/books' } Within my controller, there is the following code: def index render 'lightbox.js.erb' end ...

Passing an array from the PHP View to a JavaScript function and plotting it

Greetings, I am currently facing the following tasks: Retrieving data from a database and saving it to an array (CHECK) Sending the array from Controller to View (CHECK) Passing that array to a JavaScript function using json_encode (CHECK) Plotting the ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

Could anyone provide some insight into the reason behind this occurrence?

I just came across the most peculiar situation I've ever experienced. Check out this unique test page: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> fun ...

Modify the class name of a hyperlink using Ajax after clicking a button

I currently have four menu tabs. One tab contains a submit form by default, while the second tab displays a list of entries with each entry having a button labeled "change status." When this button is clicked, I use ajax to update the page without refres ...

Show the loading icon once to indicate that the page is waiting for an AJAX call

I am currently setting up a table that is refreshed with new data every 4 seconds using AJAX. During the initial page load, I would like to show a loading message while waiting for the AJAX to complete. Currently, I have successfully displayed the loading ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...