Post results increases on each change event

I am making an ajax POST to a servlet which returns me an array. The call is triggered on an onchange event. For the first time I receive the correct data. But from there onwards, the data keeps adding up.

For example first time onchange event occurs and array received contains [10,11] which is correct.

Second time onchange event occurs but array received contains [10,11,12,13] when it should have been just [12,13]. Thir change event will be an even longer set of data.

I tried with cache: false and same results. Please advice.

$('#drivername1').on('change', function() {
    $.post("statChartServlet", {driverName : this.value},  function(responseText) {
        alert(responseText); //this is the array data that keeps increasing


private ArrayList<String> tempArr = new ArrayList<String>();
protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {

        String driverName = request.getParameter("driverName");

        Connection conn = null;

            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

            Statement statement = conn.createStatement();
            ResultSet resultset =
                    statement.executeQuery("select racename from race WHERE drivername = '" + driverName + "'");

            while( {
        }catch (Exception e){

        //response section
        String[] strArr = tempArr.toArray(new String[tempArr.size()]);
        PrintWriter out = response.getWriter();

Answers 1

  • This line right here private ArrayList<String> tempArr = new ArrayList<String>();

    It persists between requests. Put it inside doPost. Ideally, servlets should be stateless, to prevent bugs like this.

Related Articles