retrieve dropdown menu using an ajax request

My task involves using an AJAX function call to return an ArrayList and populate the results in an HTML dropdown list. However, I have encountered a problem as my dropdown list remains empty despite my efforts.

Here is my servlet code:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Integer p = Integer.parseInt(request.getParameter("studentid"));

    ArrayList<SessionDataBean> result = new ArrayList<>();
    String sessid = null;
    try ( Connection con = JdbcUtil.getConnection()) {
        String sql= "select distinct F.SESSIONID "
                + "from Students F "
                + "where F.studentid = "+p;
        try (Statement st = con.createStatement()) {
            System.out.println(sql);
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()){
                result.add(new SessionDataBean(rs.getString(1)));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        }
    catch (Exception e) {
        e.printStackTrace();
    }
    response.setContentType("application/json");
    new Gson().toJson(result, response.getWriter()); 

    }

The AJAX function call code is as follows:

function listSession(){
  var name = document.getElementById("studentid").value;      
  $.ajax({
        url : "<%=context%>/ListSessionsServlet?studentid=" + name,
        type : "POST",
        async : false,
        dataType: "json",
          success : function(data) {
              var toAppend = '';
              $.each(data,function(i,o){
                  toAppend += '<option>'+o.id+'</option>';  <---issue might be here?
                 });

                $('#sessid').append(toAppend);
          }  
    });
 }

Lastly, here is the HTML code for displaying the dropdown list:

    <div class="cell">
        Select Session for Student
        <div class="input-control select mutiple full-size">
            <select id="sessid" name="sessid">
            </select>

        </div>
    </div>

Answer №1

The server is looking for a POST parameter called "studentid" but receives "name" instead. To fix this issue, replace

Integer p = Integer.parseInt(request.getParameter("studentid"));

with

url : "<%=context%>/ListSessionsServlet?studentid=" + name

and update it to

url : "<%=context%>/ListSessionsServlet?name=" + name

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

The communication between AWS Lambda and an SQS queue is currently experiencing a disruption in message delivery

I am facing an issue with sending a hardcoded message to SQS from Lambda. While running the lambda function locally, I am able to see messages in SQS. However, when deployed as an image, the lambda function is not working properly. I have already added Ama ...

Having trouble loading HDRI image as environment using Three.js

I recently started using Three.js and am currently tackling a project that involves utilizing an HDRI file for environmental mapping for lighting and reflection purposes. I've been experimenting with loading HDRI files using the HDRCubeTextureLoader a ...

Utilizing the reduce method to process an object and return a collection of objects

I have a complex object that I'm trying to transform using the reduce method, but I'm struggling to figure it out... Here is the structure of my object: const object = { ... } My goal is to create a new object with keys that are a combinatio ...

Can you clarify the functionality of this loop? I am having trouble grasping how it produces the final result

Seeking clarification on the highlighted section] https://i.sstatic.net/dyrKS.png I need assistance in understanding how the use of "text" helps to print the following literal. ...

Applying ng-class based on conditions to icons within table cells

In my table, I am using ng-repeat to bind cells with data. One cell contains edit, save, and delete icons. When an order is posted, the delete/save icons should be disabled and displayed in a different color. While I can disable the click event of the icon ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

Attempting to save the result of a fetch call into a variable for the purpose of rendering it as a list in a

I'm attempting to fetch the top 5 NFT collections based on volume and display them in a table format. However, I'm facing an issue where the data is not being mapped correctly and when I click the "get" button, all content on the webpage disappea ...

Encountered an issue while executing the next build process

Every time I run npm next build, it throws an error message. Despite my efforts to search for a solution online and installing the "extract-text-webpack-plugin," the issue persists. The error being thrown is as follows: > next build (node:8136) Depre ...

Is there a way to use JavaScript to change the text displayed in this ASPX control?

On an ASPX page, I have the following input control: <input tabindex="0" class="_f_ql _f_rl textbox allowTextSelection placeholderText" role="textbox" aria-labelledby="MailCompose.SubjectWellLabel" autoid="_f_B2"></input> I am limited to inje ...

Enclosing sets of lists with div containers

My Objective: <ul> <li class="group4"> <ul class="group2"> <li class="first">stuff</li> <li class="last">stuff</li> </ul> <ul class="group2"> ...

Changing the property types in subclasses in Java Android can be achieved by using overrides

I'm currently working on incorporating the MVP (Model-View-Presenter) pattern into my Android app, but I've hit a roadblock. I'm trying to create an abstract base presenter with a view class property of a generic type ViewInterface. However, ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

RequireJS has an unbreakable reliance on the library

For my Angular + Require project, I encountered an issue while trying to package the application with r.js using: node r.js -o app.build.config.js Despite everything working fine, the library files were not found on the specified path. Instead, the depen ...

Any alternatives to setInterval for checking if a file has been modified?

Is there a more efficient way to check if a file has been modified on the server than my current method of using setInterval and AJAX calls to a PHP script? I'm wondering if there is a better approach similar to how I used mutationObserver for somethi ...

Revising variables in Java Script

How can I shuffle a list of variables in JS and maintain the order while changing their values? The following code snippet demonstrates what I am trying to achieve. <p id="demo"></p> <script> var gen = "male "; var race = "white"; var ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

Hiding the icon if there are no child elements present

Currently, I am in the process of constructing a TreeView using the Treeview component from Material UI, which can be found at this link. The component I have designed below is responsible for fetching data when a node is expanded. The tree structure is s ...

Validating inputs with pristine Vue.js

I am working on creating a vue.js based form validation system that validates input on-the-fly without the need for page refresh. Currently, I have implemented the following code for email field validation: <div class="container" id="forms" > <l ...

Oops! We are facing a bit of a hiccup here. It seems we are unable to access the org

Every time I execute the following command: mvn clean test I encounter this specific error message: [ERROR] Failed to run goal org.apache.maven.plugins:maven-compiler-plugin:3.2:testCompile (default-testCompile) on project suman: Compilation failu ...

Troubleshooting Problem with Website Responsiveness on iPhones Using Bootstrap 5

I am currently experiencing a challenge involving the responsiveness of a website I am developing, particularly when it comes to iPhones. The site utilizes Bootstrap 5 and displays correctly on Android devices and in Chrome Dev Tools. However, upon testing ...