`The success callback function does not get invoked after an AJAX request is made to the servlet

I am currently working on implementing a dependent drop-down list feature. I have developed a JSP page where I call a servlet through an AJAX request. In the servlet, I use a JSON object to retrieve values for the dropdown list. While the values are being properly retrieved in the JSON object, I am facing an error where the request is not completing successfully (the error method is triggered instead of the success method).

Below is my AJAX code:

$.ajax({ 
    type: "GET",   
    url: "MyServlet?index="+listindex,
    datatype: 'JSON',
    error: function() {
        alert("Error");
    },
    success: function(data) {
        try{
            var citiArray = JSON.parse(data);

            if(citiArray != null){
                for(var s=0; s<citiArray.length; s++){
                    var serial = citiArray[s];
                    //populating the drop-down list
                    $("#dname").append($("<option></option>").val(serial.authors1).html(serial.authors1));
                }
            }
        } catch(err){
            alert(err);
        }
    }
});

My Servlet code: MyServlet.java

public class MyServlet extends HttpServlet {
   /**
 * @see HttpServlet#HttpServlet()
 */
public MyServlet()  {
    super();
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try { 
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/orcl" ,"hr", "password");

        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json"); 
        PrintWriter out = response.getWriter(); 

        String listindex = request.getParameter("index");
        out.print(listindex);
        String query2 = "select module from course where cname=?";
        PreparedStatement st2 = con.prepareStatement(query2);
        st2.setString(1,listindex);
        ResultSet rs2 = st2.executeQuery();

        JSONArray uniList1 = new JSONArray();
        while(rs2.next()) {
            uniList1.add(rs2.getString("module"));
            //System.out.println(rs2.getString("module"));
        }

        JSONObject obj = new JSONObject();
        obj.put("key", uniList1 );
        System.out.println(obj);
        out.print(obj);
    } catch(Exception e) {
        e.printStackTrace();
    }
}
}

web.xml:

<servlet-name>MyServlet</servlet-name>  
<servlet-class>com.dac.MyServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>MyServlet</servlet-name>  
<url-pattern>/MyServlet</url-pattern>  
</servlet-mapping>  

Thank you, Rohit

Answer №1

Ensure a response is sent in the event of an exception

 catch (Exception e) 
{
    // TODO Auto-generated catch block
    e.printStackTrace();
    //send the response
    out.print(e.getMessage());
}

To get a detailed error description, use:

 error: function (theRequest, theStatus, theError) 
 {
    alert(theRequest.responseText);
}

instead of

  error : function() {

        alert("Error");
          }

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

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Generate an animated sequence transitioning smoothly from the left side to the center

I am in need of creating an animation that will cause a menu to appear from the left side of the screen when a button is clicked. The menu should expand to cover 55% of the width of the main page. You can view a demo of this animation on JSFiddle by follo ...

Troubleshooting the issue of missing object in Django template

I keep encountering the issue that json is not serializable. views.py def get_post(request): if request.is_ajax(): if request.method=="GET": craves = CraveData.objects.filter(person=request.user) print craves ...

Tips for integrating an image with form.serialize() function?

When attempting to add an image in the form.serialize, it appears to not be functioning properly. The form in question is provided below: var frm = $('#id_article_form'); var formData = $('#id_article_form').serializeArray(); formDat ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

The Bootstrap modal seems unable to bring the button back

Despite my code functioning properly, the button is not going backward after being clicked. Check out my output here <a href="#myModal" role="button" class="btn btn-large btn-primary" data-toggle="modal">Launch Demo Modal</a> Here is the HTML ...

Instructions for redirecting to "http://localhost:4200/shops/shop1/dashboard" following a successful authentication through Auth0 in an Angular

Post-login, Auth0 redirects only to the root URL at http://localhost:4200 instead of http://localhost:4200/shops/shop1/dashboard. The official documentation from Auth0 states: After successful authentication, callbacks will only be made to specific URLs. ...

Reveal or conceal the footer section as you reach the end of the webpage

My webpage layout consists of a fixed nav-bar at the top, a drop down sidebar, a <div> element with an id of content, some content inside the <div>, and a bottom <div> with a fixed position. I am trying to hide the bottom <div> whe ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...

Exploring the wonders of useState in React/JavaScript - a comprehensive guide

I encountered an issue while attempting to map an API request from a useState hook. The fetch operation functions correctly and returns an array of objects that I then assign to my useState variable. Subsequently, when I try to map over the useState varia ...

Accessing stored web pages / Browser as an interactive interface

I have a couple of questions I need help with. The first one is about how to open a saved HTML file in a browser without an internet connection. Next, I'm looking for advice on using the browser as a user interface for a desktop image viewing program ...

What is the best way to manipulate and update individual counters in React components?

I developed a ticket ordering system for a project, but encountered an issue where increasing the quantity of one ticket also resulted in the incrementation of the other ticket's counter. I suspect this occurs because only one value is stored in the s ...

Ways to conceal buttons according to your 'occupation'?

I am currently developing an application and I would like to have certain buttons displayed based on the user's $job. There are four job roles stored in mysql databases: student teacher staff principal, The signup button should only be visible to te ...

Retrieving data from Jersey by utilizing jQuery and Ajax

In my webservice, users have the ability to download either a docx or pdf file. Here is the code snippet that enables this functionality: @GET @Path("explicacionOperador/explicacion_operador_ticket_{id_ticket}.pdf") @Produces("application/pdf") public Res ...

Instantiate an model when the AJAX call successfully returns

There is a User model defined as: var UserModel = Backbone.Model.extend({ defaults: { handle: '', email: '', uuid: '', userpic: '', tokenlogin: '' } }); A c ...

Updating the parent table from a partial view can be achieved effortlessly with the help of Ajax

Within my system, there is a table displaying various courses along with a Select button next to each course in a row. Clicking on the Select button reveals a list of enrolled users for that particular course. The Course entity includes a navigation proper ...

Using AngularJS to Nest ng-view within ng-repeat

I have a collection of items. Each item has buttons to display its details and comments within this ng-view section. It is necessary for the user to view all available product details on one page, for example. Below is the HTML list: <div ng-controll ...

What is the reason for an object not being generated when using executeScript in Protractor?

In the context of a Protractor script testing an AngularJS app, I have included the following code within a describe block. beforeEach(function() { browser.get('index.html#/device_list'); browser.executeScript("chrome.bluetooth = {};"); br ...

Unable to utilize the onAngularGridCreated emitter

I'm currently facing an issue with the Angular Slickgrid library. I need to customize the sorting button function by using the onAngularGridCreated event, which should return the instance of my grid. However, when I include the following code in my an ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...