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

Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container: $('img').each(function(i){ var parent_width = parseInt($(this).parent().width()), image_width = parseInt($(this).width()); ...

Incorporate the jquery lazy load plugin alongside ZURB foundation data-interchange for optimal performance

Currently, I am engaged in a project that involves utilizing the ZURB foundation framework alongside its data-interchange feature to display various images based on different screen sizes. To learn more about this method, please visit: You can also explo ...

Having trouble choosing an option from the dropdown menu with Puppeteer Js

I need help with Puppeteer JS to select the initial element in a dropdown. Any suggestions? Once I input the city name in the text field, I want to choose the first option from the dropdown menu. const puppeteer = require('puppeteer'); (async ...

What is the best way to route a localpath to a different page including parameters in Nuxt Js?

Hello, I am facing an issue where I need to pass parameters in the URL to another page in NuxtJs props: { idPending: { type: Number, required: true } }, methods: { fetchpage() { const orderId = this.idPending; this.$rou ...

Displaying an email exist error message is important when updating an email address, and it is necessary to validate both the

      My code is triggering an email exists error when I remove NOT EXISTS from the SELECT query. However, it also incorrectly claims that my current email already exists when I try to update it. How can I modify the select query to handle the email e ...

What is the best method to include spacing between strings in an array and then combine them into a csv-friendly format?

The method I am currently employing involves the following: var authorsNameList = authors.map(x => x.FirstName + ' ' + x.LastName); Yet, this generates an outcome similar to this: Bob Smith,Bill Jones,Nancy Smith Nevertheless, the desired ...

When using Ajax in Jquery and expecting data of type JSON, the response always seems

Looking to create a basic jQuery Ajax script that checks a user's discount code when the "Check Discount Code" button is clicked? Check out this prototype: <script> jQuery(function($) { $("#btn-check-discount").click(function() { c ...

Importing a module directly from the umd distribution may yield a distinct outcome compared to importing it

Within my Vite/Vue3 application, I am importing two identical umd.js files: One is located at node_modules/foo/bar/dist/foobar.umd.js (imported with alias @foo = node_modules/@foo). The second .umd.js file can be found at <root dir>/foo/bar/dist/ ...

"Enhance Your Website with Javascript: Combining and Incorpor

I'm struggling to assign the selected attribute to the option value that is already rendered within the object. However, despite the values being equal, the selected attribute is not being added. Could this issue be related to the appending process? ...

Unable to access View variables set in App controller in Cakephp 3 when rendering certain templates or during AJAX requests

I have set various view variables in my App controller like company name, address, and contact information that change depending on subdomains to make them available across all view templates. However, I am facing difficulties in understanding why they are ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

What is the best way to make a select tag read-only before the Ajax request is successful

Is there a way to make a select tag read-only before an Ajax success? I tried using this code, but it didn't work: $("#tower").prop('readonly', true); Then I tried this alternative, but I couldn't get the value from the select tag: ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Exploring the Differences Between Next.js Script Components and Regular Script Tags with async and defer Attributes

Can you explain the distinctions between the next js <Script /> component rendering strategies such as afterInteracive, beforeInteractive, and lazyLoad, as opposed to utilizing a standard <script /> tag with attributes like async and defer? ...

JavaScript: Creating Custom IDs for Element Generation

I've been developing a jeopardy-style web application and I have a feature where users can create multiple teams with custom names. HTML <!--Score Boards--> <div id="teamBoards"> <div id="teams"> ...

Struggling to locate the index of the matching object within an array of objects?

There is a dataset available: var data = { "variants": [{ "quantity": "20", "varientId": 8, "currency": "YEN", "extraField": { "Size": "1 ...

The header element in JSP is concealed prior to the page being fully loaded

I have a basic login page titled login.jsp that includes header and footer content. The header content is stored in pageheader.jsp which consists of the header body tag, etc. I am looking to hide the header and footer elements specifically on the login pa ...

"What is the best way to connect a md-input to the value of a md-slider

I'm in the process of developing an application using Angular 2.0/meteor, and I'm facing a challenge with binding an input to md-slider. Below is the HTML code for the component: <div class="panel-body"> <form [formGroup]="filtreFor ...

What is the best way to sequence the functions in an AJAX workflow?

I'm currently working on optimizing the execution order of my functions. There are 3 key functions in my workflow: function 1 - populates and selects options in a dropdown using JSON function 2 - does the same for a second dropdown function 3 - ...

The function `React.on('languageChanged')` is not effectively detecting changes in the language

I'm new to working with React and I'm looking for the best way to detect when a user changes their language preference. I am currently using next-translate to handle translations, but for some resources that come from an API, I need to update the ...