Is it achievable to send information back to a Servlet from JavaScript?

I am currently working on setting up a Servlet that utilizes JDBC for database interactions.
My goal is to allow users to log in through a login form and then view the list of available databases in MySQL. I am implementing this functionality dynamically within the servlet by generating a dropdown list of the databases visible to the user.
Once a user selects a database from the dropdown menu, JavaScript is used to identify the selected database. I am now looking for a way to pass this value from JavaScript back to my servlet. The idea is to use the selected database information to display a list of tables within that database to the user. Is there a way to achieve this? If not, are there alternative methods to accomplish the same goal?

Below is an excerpt of the code responsible for generating the dynamic dropdown menu:

                ResultSet r = dbmetadata.getCatalogs();
                ResultSetMetaData metadata = r.getMetaData();
                int colCount = metadata.getColumnCount();
                int i;

                out.println("<select id='db' name='db' onChange= 'myFunction();'>");
                out.println("<option value = -1>--Select Database--</option>");
                int value = 1;
                while(r.next())
                {   
                    for(i=1;i<=colCount;i++)
                    {   
                        out.println("<option value = " + value + ">" +  r.getString(i)  + "</option>");
                    }
                    k++;
                }
                out.println("</select>");

The accompanying JavaScript code is structured as follows:

function myFunction()
{
var select = document.getElementById("db");
var dbSelected = select.options[select.selectedIndex].text;
var x = document.getElementById("dbs");
x.innerHTML = "You have selected " + dbSelected;
};

Thank you for your assistance :)

Answer №1

If you want to communicate with a servlet, one option is to send a post request. Here's how you can do that:

  // Send the data using post
    var posting = $.post("/GetAllTables",{dbname:"myydb"});

    // When the POST request is done..
   // data: The output printed in servlet
     posting.done(function(data) {

            // Put the results in a div
            $("#view").append(data+"<br/>");

           //you can also take data string and split it with ,(comma) and append this tablenames to a dropdown etc.

     });

In your servlet code:

String dbName=request,getParameter("dbName");

//generate all table name in string like

String tables="table1,table2,table3"

// Get PrintWriter obj using getWriter() in HttpServletResponse
PrintWriter pw=res.getWriter();

// Print, that's it!!
pw.println(tables);

Alternatively, you can use ajax instead of a post request. With ajax, you can also send the table name in JSON format.

For more information, check out Using Post or Using Ajax.

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

Animating a camera along a predefined path in A-Frame to maintain focus on a subject

I have been experimenting with animating a camera using the alongpath component, but I am struggling to keep the camera focused on a target. Despite trying both orbit-controls and look-at components, I can't seem to get them to work properly. It seems ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

My picture is refusing to load... Why does it keep saying "image not found"? Any thoughts on why this might be

I've been trying to display a picture of myself on my html canvas, the image is stored in the correct folder. However, I keep encountering a strange error (shown above) and I can't seem to figure out what's causing it. If you have any insigh ...

Discover the method of connecting to a unique JavaScript trigger while utilizing IJavaScriptExecutor

In our web application, we have an event called timelineEventClicked that is created by a custom trigger. canvas.addEventListener('click', function (evt) { evt.stopImmediatePropagation(); var mousePos = ge ...

"Enhancing User Experience with Animated Progress Bars in Three.js

Is there a way to create a progress bar animation in three.js? I've been grappling with this issue for quite some time now. I attempted to replicate the html5 video player progress bar method, but unfortunately, it doesn't seem to be compatible w ...

Triggering a jQuery event when a CSS property is altered

My current approach involves utilizing the .animate method to shift a div 100px to the right in just 1 second. Essentially, this means moving by 1px every 10ms. I am now exploring whether there exists an event that could be triggered after each individual ...

The height of divs spontaneously changes after resizing without any instructions

I am developing a jQuery function to vertically center an element. The function is triggered on load and here is the code: JQuery var $window_height; function Centerize(content) { content.css('margin-top', (($window_height - content.height( ...

Trouble with Global Variable Allocation in jQuery Ajax

I've got a script that includes a jQuery Ajax call: <script type="text/javascript"> $(document).ready(function() { var timer; $.ajax({ type: 'POST', url: 'closettime.php', success: function( res ) ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...

Why is the displayname not being returned by the query like it does in phpMyAdmin?

I'm facing an issue with this code - it works perfectly fine when executed in phpmyadmin, but when I try running it in PHP, it doesn't work as expected and returns "0 results". Here is the SQL query: SET @felhasz := (SELECT user_id FROM `items_ ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...

Transfer razor javascript calls in Blazor WebAssembly to a separate class

Scenario Description Greetings, I am currently working on a Blazor WebAssembly project that involves JavaScript interop. Initially, I had this functionality working in a .razor page. However, I now intend to encapsulate and centralize these JavaScript inv ...

Determining html column values using a related column and user input

Is there a way to populate an HTML table column (using Javascript or jQuery) based on the values in another column and an input field? For instance, if I input the number 115 into the field, then the advance column should display a value of 1 for each ath ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Error in Django: The specified table does not exist when running the command "python manage.py migrate"

After accidentally dropping a table related to an app, I attempted to run the syncdb command again. python manage.py migrate However, an error occurred: django.db.utils.ProgrammingError: (1146, "Table 'homeapp_enroll_course' doesn't ex ...

The UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...

What is the best approach for populating foreign key values when transferring information from a flat file to a relational database using SQL?

Currently, I am faced with the challenge of managing 3 different tables in my database. The first table contains all the information that needs to be extracted and split into two separate tables. [flat file] name / team / town [team table] teamID/ team ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Employing switch statements to match regular expressions in JavaScript

Could someone help me with converting my if statements to a switch statement for evaluating regex? I have been struggling to figure it out and would appreciate any guidance. Below is the code I have attempted: var username = $('input.username'), ...