"Surprising Outcomes When Using JSP, JavaScript, and Servlet Together

I am facing an issue with a form on a jsp that calls a javascript function, which in turn calls a servlet. The problem is that the code works intermittently, and when it does reach the servlet, the parameters come back as null. It's also strange that it alternates between using the doGet and doPost methods even though I have specified "POST". Can someone help me troubleshoot this?

JAVASCRIPT:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
  $().ready(function() {
    $('.my_button').click(function() {

        var dataf = 'email=' + $('#email').val()
                + '&password=' + $('#password').val();
        $.ajax({
            url: "http://localhost:8080/RetailerGui/loginServlet",
            type: "POST",
            data: dataf,
            dataType: "JSON",
            success: function(data) {
            alert(data);

            }
        });

    });
});
</script>

JSP FORM:

              <form id="newsletter" method="POST">
                  <div class="wrapper">
                    <div class="bg">
                      Email:<input type="text" id="email">
                    </div>
                     <div class="bg">
                      Password:<input type="password" id="password">
                    </div>
                    <button class="my_button" name="login" >login</button>
                  </div>
                </form>

SERVLET "loginServlet":

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
       String email = request.getParameter("email");
        String password = request.getParameter("password");
        String loginResult = login(email,password);
        System.out.println("EMAIL:" +email);
        System.out.println("PASSWORD:" +password);
        System.out.println("IM INSIDE GET!!!!");
        response.getWriter().write(loginResult);

    }

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String loginResult = login(email,password);
    System.out.println("IM INSIDE POST!!!!");
    response.getWriter().write(loginResult);
}

If you need any other information or further clarification, please let me know. Thank you for your assistance.

Answer №1

Thanks to the advice from this community, I was able to find the solution to my problem! Check it out here

Answer №2

Here are three key points to consider:

  1. When working with HTML, make sure your button is set to type="button" to prevent it from automatically submitting the form to the current URL. You can refer to this link for more information.
  2. In your HTML form, include onsubmit="return false" as an added precaution to ensure that the form does not inadvertently submit to the current URL.
  3. Lastly, take a moment to review what the processRequest function does in your servlet code - understanding its purpose will help ensure proper functionality.

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

"Exploring the world of Material UI styling with ReactJS: A deep dive

I've been busy developing a small web application using ReactJS and Material UI. In the documentation examples, many components include useStyles within the code. I've decided to follow suit and now have a useStyles function in each of my compone ...

Discover the best way to reference a JavaScript variable within an HTML form textfield

I'm having trouble with a script that is supposed to display the selected value from a drop down list in a text field on an HTML form. When I select an option, the value is not appearing in the text field. Can someone please assist me with this issue? ...

The MDBDataTable features header sections at both the top and bottom, but the filters UI seems to be

Currently, I am working with MDBDataTable and encountering an issue with the double heading that appears both on top and bottom of the table. I am unsure how to remove it. The code snippet in question is as follows: There is a function that retrieves and ...

Unlocking the Power of Angular: Transforming Input into Results

I'm currently exploring how to utilize an input field and fetch a response using Angular directly within the script. As a beginner, I came across this script on codepen. At the end of the code, I've attempted to make a call but haven't compl ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Implement the heightmap onto the SphereGeometry using three.js

[UPDATE: Refer to this jsfiddle for a live demo along with the relevant code] I am using three.js to create visualizations of celestial bodies with distinct characteristics. While there are no specific examples available on implementing spherical heightm ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Bounding box in ThreeJS for a 3D entity represented in 2D dimensions

I'm currently trying to calculate the area on my screen that is occupied by a 3D object. Despite searching online, I have been unsuccessful in finding a solution to this problem. The function geometry.computeBoundingBox() only provides me with the 3 ...

Is it possible for Java to retrieve pending Android OS updates?

I'm currently working on a Java project to determine whether the Android OS has an update pending. I came across a suggestion in AndroidDeveloper that involves creating a Device Policy Controller (DPC) to install a "work profile" on the device. Howeve ...

Versatile Function for Handling Dropdown Changes

I am faced with the challenge of executing a javascript function when multiple select elements are changed. I want to create a versatile function that can be set as the onchange method for various select elements. The following code accomplishes this task ...

Tips for ending the setInterval function within a do while loop using jQuery

My goal is to stop the setInterval function after the do-while loop meets a certain condition. The issue I am facing is that, even when the while loop's condition is met, the setInterval continues to run. do { setInterval(Vinformation(),500); } w ...

JavaScript encountered an issue as it attempted to reference the variable "button" which was

I am currently working on developing a new API, but I have encountered some issues with JavaScript: Below is my JS/HTML code snippet: const express = require('express'); const app = express(); const PORT = 3000; submit.onclick = function() ...

Adjust the minimum and maximum values of the Y-axis based on the scale of the X-axis

Currently, I am faced with the challenge of adjusting the Y-axis to scale with changes in X-scale. I have a long unixtime value Array for initializing a flot chart, along with buttons to modify the scale. However, I am struggling to synchronize the Y-axis ...

Once the final row in the table is removed, the width of the second cell in the top row will be set to 0

Can anyone help with an issue I'm having on my website? I created a basic web page with some Javascript that allows for inserting and deleting table rows. However, I've noticed that in IE6, when I delete the last inserted row, the second cell of ...

Troubleshooting Issue with JQuery Date Picker: Date Not Valid

Encountering an issue when using the date from JQuery DatePicker in an SQL Statement variable, resulting in an error of invalid datetime string. Even after attempting to format it with DateTime.Parse or Convert.DateTime. JQuery DatePicker <script> ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...

Creating dropdown lists with images using ajax and json: A step-by-step guide

I am looking to create a simple drop-down list with images as the values. My goal is to utilize ajax to display images on the options list and trigger partial post backs when selecting values from the list. Below are the provided code snippets. <html&g ...

Steps to eliminate cucumber tags from the extent report

Some of the test cases in my cucumber feature file have multiple tags such as @smoke, @regression, @homePage, @e2e. I want to ensure that when triggering test cases based on the smoke tag and generating an extent report, only the specific trigger tag is di ...

Loading STL files can sometimes lead to issues when accessing the world matrix incorrectly

While working on a three.js project, I encountered some issues with loading vertices from an STL file and converting them to world coordinates. It seems like the matrix application isn't working properly, and I suspect it could be related to the loadi ...

LWJGL - Issues with rendering to framebuffer leading to incorrect output

I am attempting to direct all my renderings to a framebuffer instead of the backbuffer, while utilizing LWJGL. For the graphics, I perform the following steps: Setting up the display and configuring OpenGL: try { Display.setDisplayMode(new ...