Retrieve servlet input with JavaScript and use Ajax to set the value to a text box

I am working on a servlet that retrieves values from properties files. I need to pass these values to my JavaScript using AJAX and set them in a textbox. As I am new to Ajax, I would appreciate if someone could help me by analyzing the code.

SERVLET

       @WebServlet("/PopulateProperties")
      public class PopulateProperties extends HttpServlet {
     private static final long serialVersionUID = 1L;
     Properties prop = new Properties(); 
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String serverName=request.getParameter("servernameDD");
    List<Map<String,String>> returnObj = new ArrayList<Map<String,String>>();
    String[] servers = getSearchAttr("servers");
    if (servers != null && servers.length > 0) {


        String[] lookfor = getSearchAttr("servers_lookfor");
        for (String server : servers) {
            Map<String,String> obj = new HashMap<String,String>();
            if (lookfor != null) {
                for (String look : lookfor) {
                    //System.out.println("looking for :"+look);
                    String value =  prop.getProperty(server+"_"+look);
                    if(server.equalsIgnoreCase(serverName)){
                        if(look.equalsIgnoreCase("Links")){
                        String getlook=prop.getProperty(look);
                        String getlink=prop.getProperty(server+'_'+look,"Links");
                        System.out.println("Hello" +getlink);
                        System.out.println(getlook);
                        request.setAttribute("serverLink", getlink);

                        }
                    }
                    if (value != null) {
                        obj.put(look, value);
                    }
                    request.setAttribute("servers", server);
                    request.setAttribute("lookfor", look);

                }           

            }       
            //System.out.println("Object :"+obj);
            returnObj.add(obj);

        }


    }
    response.sendRedirect("updateserverstatus.html");

        }






private String[] getSearchAttr( String property){
    String lookfor = prop.getProperty(property,"");
    String[] ret = {lookfor};
    if (lookfor.contains(",")) {
        return lookfor.split(",");
    } else {
        //System.out.println("comma not present in "+property);
        //System.out.println("webservice :"+lookfor);
        return ret;

        }

     }

I have attempted the following Ajax request, but I keep encountering an "undefined error" for serverLink variable.

function OnSelectionChange(){


$.ajax({
    type: "POST",
    url: "/PopulateProperties",
    data: "{Links: " + serverLink + "}",
    success: function(result){
        alert(result.d);
        console.log(result);
    }
});
  }

Answer №1

Instead of using a servlet to fetch and forward data, a more effective approach is recommended:

Within your servlet, simply return the properties data in JSON format. You can find guidance on how to do this here.
Then, retrieve this data using AJAX in your HTML page and update the text content of a textarea element accordingly.

Answer №2

To ensure code coherence, it is advisable to create a dedicated servlet specifically for this purpose. Pass all necessary parameters to narrow down the data retrieval process.

For simplicity, consider returning either the value itself or presenting the data in JSON key-value pairs.

If your textbox has the following structure:

<input type="text" id="prop_txt">
, then the corresponding ajax code would be:

$.ajax({
  type: "POST",
  url: "/PopulateProperties",
  data: "{A:(..a value..),
          B:(..b value..),
          ....
          ....
          (..all the required parameters..)
         }",
  success: function(result){
      //alert(result.d);
      console.log(result);
      $('#prop_txt').val(result);
  }
});

I trust that this information proves helpful for your project needs.

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

Text from the GET request is not being displayed in the textbox, although it is appearing in the div when using Jquery and Ajax

Currently, I have a webpage that features a text box which can be updated in real-time as the user types and is immediately saved to the database. Here is the code for my textarea: <textarea id="text"></textarea> My objective: If a user ope ...

Eliminate the bottom border from the MUI Input component

Is there a way to get rid of the bottom-line borders on these input fields? I attempted using CSS but couldn't find a solution for this component -> <Input type={"text} /> ? https://i.sstatic.net/4QpWym.png ...

JavaScript: retrieving undefined value from a text element

My goal is to retrieve the text entered into each textbox by querying and looping through their ID tags. However, when I attempt to print what I have retrieved, it always displays "undefined". Seems like your post consists mostly of code: </h ...

The type 'Node' does not have the required attributes

Could anyone shed some light on what might be causing the issue described below? Your insights are greatly appreciated. The problem lies within the line of code: clone = thead.cloneNode(true); The error message reads: 'Type 'Node' is missin ...

Adjust the window size smoothly to accommodate various height dimensions

Providing Some Background: I am currently developing a Chrome Extension where users have the option to launch it via the default "popup.html", or detach it from the top right corner to use in a separate popup window using window.open. This question also ...

Is the background image slowly disappearing?

Instead of using the background property for a background image, I have opted for a different style. Here is how I implemented it: <div id="bg"> <img id="bgChange" src="image/image.jpg" /> </div> This is the corresponding CSS code: ...

Utilizing the super method within a sails.js controller

Is there a way to call the default parent method of a redefined standard method in a controller created in sails.js? module.exports = { create: function(req, res) { //test some parameters if (condition) { //call regul ...

Using a for loop to call a Node.js request function

I have arrays consisting of 8 elements each var array_pullrequest_id=["335","328","326","323","322","314","295","291"]; var array_uniqueName=["<a href="/cdn-cgi/l/email ...

Mongoose only pushes the ObjectID, and not the entire document

I run a recipe blog website where each recipe has its own set of comments. All comments are stored in a collection, but when I associate a comment with a specific recipe, only the ObjectID gets saved. Below is the code snippet: Recipe model const { D ...

How to activate a single element within a React array

I am currently working on developing a comment system similar to the one found on YouTube. In my setup, when I click on modify, all comments turn into input fields, but only the selected input should be modified. How can I trigger only the element I clicke ...

A guide on seamlessly transitioning from a mobile website to the corresponding native app

I am currently working on a mobile website project. This website is built using basic HTML and is accessed through a URL on a web browser, not as a native app or through PhoneGap. The client has requested links to their Facebook, Pinterest, YouTube, Twitt ...

Can you explain the distinction between 'url.searchParams' and 'URLSearchParams' in Node.js?

Can you explain the primary distinction between URLSearchParams() and url.searchParams? In what ways do these two differ? Let's consider the following example: var searchParams = new URLSearchParams("q=URLUtils.searchParams&topic=api"); url = n ...

Encountering a data property error while trying to render ejs using axios

I am encountering an error message "TypeError: Cannot read property 'data' of undefined" when trying to display results.ejs using data from an API. Can someone help me identify what's incorrect with the rendering code? Thank you. index.js: ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

What are the steps to integrating JavaScript autocomplete into a website?

I am relatively new to the world of programming, particularly when it comes to JavaScript/jQuery. I have been searching online for a solution to enable autocomplete in my search feature, but despite trying various approaches found on the internet, I have y ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

What is the best way to add multiple lines of text to a webpage using the span element?

Currently, I am developing a game that involves using a map, which consists of multiple lines. My question is whether it is possible to have the span tag cover multiple lines while ensuring that each line ends with a new line character. Below is an exampl ...

Error: The method area is not supported for this.mesh.geometry

Recently, I've been experimenting with JavaScript, Three.js, and Leapmotion. To enhance my program, I decided to incorporate the leap widgets library which can be found here. However, after investing numerous hours into this project, I encountered a ...

My gaming console is malfunctioning and the controller is unresponsive

I developed an application with a login page and a controller structured like this: ----> --->over here :) (function(){ 'use strict'; angular .module("loginApp",[]) .controller("loginCtrl",loginCtrl); loginCt ...

What steps can I take to ensure that my dynamically loaded script is fully loaded prior to executing a particular function?

I am facing an issue with a dynamically loaded script in a component. The script contains a function that is used within another function like window["scriptFunction"]. The problem arises when this function is sometimes called before the script i ...