What is causing my page to refresh when making an Ajax call? (e.g. triggering the servlet request again

I'm currently learning about RESTful web service implementation using Java in my development environment, which consists of Netbeans IDE with GlassFish v3.

Within my project, I have a specific page URL called /inventoryList, which is mapped to the InventoryApp.java servlet in the web.xml file.

Here's an example of the web.xml configuration:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet>
        <servlet-name>inventoryServlet</servlet-name>
        <servlet-class>local.test.servlet.InventoryApp</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>inventoryServlet</servlet-name>
        <url-pattern>/inventoryList</url-pattern>
    </servlet-mapping>
</web-app>

The purpose of this servlet is to retrieve inventory item information from a database and display it on the corresponding JSP page.

In the provided example, the JSP file named inventory.jsp contains the necessary logic to handle the retrieval and display of inventory items:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <script type="text/javascript">
        //Ajax code here
        </script>

    </head>
    <body>
        <h1>Inventory page</h1>

        <table border="1" cellspacing="1" cellpadding="5">
            <th>id</th>
            <th>amount</th>
            <c:forEach items="${inventoryList}" var="inv" >
                <tr>
                    <td>${inv.id}</td>
                    <td><a href="" onclick="ajaxGet(${inv.id})">${inv.amount}</a></td>
                </tr>
            </c:forEach>
        </table>
        <hr />
        <div id="inventoryItem">
        </div>


    </body>
</html>

As you can see in the provided JSP file, each inventory amount value is displayed as a link. When clicked, an Ajax call is triggered to retrieve additional details about the specific inventory item.

The corresponding REST service implementation for handling this Ajax request is shown in the provided example code:

package local.test.jaxrs;

import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import local.test.dao.InventoryDao;
import local.test.session.Inventory;

@Path("/inventory")
public class InventoryResource {
    @Context
    private UriInfo context;

    /** Creates a new instance of InventoryResource */
    public InventoryResource() {
    }


    @Path("{inv_id}")
    @GET
    @Produces("text/html")
    public String getJson(@PathParam("inv_id") String inventory_id) {
        System.out.println("Handling GET request");

        Inventory invBean = new Inventory(Integer.valueOf(inventory_id));
        InventoryDao invDao = new InventoryDao();
        List<Inventory> inv = invDao.findById(invBean);

        String html = "<b>" + inv.get(0).getId() + "</b><br /><b>" + inv.get(0).getAmount() + "</b><br />";

        return html;
    }
}

When testing the implemented code, everything seems to be working fine initially. However, there is an issue where the retrieved inventory data briefly appears on the page and then disappears.

After investigating with tools like Firebug and examining the GlassFish v3 server logs, it was discovered that the InventoryApp.java servlet is being called again at the end of the process, which triggers a redirect to the /inventoryList page.

This behavior seems strange because Ajax requests should not cause the entire page to refresh. The issue might be related to the mixing of servlets and RESTful services in this project.

If anyone has any insights or suggestions on how to resolve this issue, your help would be greatly appreciated as I have been trying to resolve this for several days now.

For reference, here's an example snippet from the InventoryApp.java servlet code:

package local.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.dao.InventoryDao;
import local.test.session.Inventory;


@WebServlet(name="InventoryApp", urlPatterns={"/InventoryApp"})
public class InventoryApp extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InventoryDao invDao = new InventoryDao();
        List<Inventory> invList =  invDao.findAll();

        System.out.println("================= do get servelt ===" + invList.get(0));

        request.setAttribute("inventoryList", invList);
        request.getRequestDispatcher("inventory.jsp").forward(request, response);
    }
}

Answer №1

<a href="" onclick="ajaxGet(${inv.id})">${inv.amount}</a>

delete the href attribute

<a onclick="ajaxGet(${inv.id})">${inv.amount}</a>

or revoke the promotion of the click event

<a href="" onclick="ajaxGet(${inv.id}); return false;">${inv.amount}</a>

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

Implementing Ajax calls in Spring Boot with Thymeleaf

I am attempting to make a Spring Boot controller call from an Ajax Request: $('#female').click(function(){ $('#analysisTable').DataTable( { "ajax": '/analyse/female' }); }); The purpose of this is to populate a ...

RememberMe feature in ZF2 combined with two AJAX calls led to the unsuccessful destruction of the Session object

Currently facing an issue: Utilizing ZF2, when I click a link in the main navigation, the subnavigation and content load via AJAX (two requests). Upon using class AuthStorage extends Storage\Session { public function __construct($namespace = nu ...

When trying to run updated test cases in Eclipse for Selenium, Maven, and Jenkins, they do not execute properly. It seems that the changes take effect only when the script is

Having automated my test cases using Selenium, Maven, and Jenkins, I encountered the following issue: For instance, after creating a class test.java with 5 test cases, everything runs smoothly when executed from Eclipse or Jenkins. However, upon adding tw ...

What is the best method for retrieving the value of a nested key in a JSON object stored in a MongoDB database using Java?

Here is the JSON structure I am working with in order to extract the phone number: "_data" : { "Variable key" : { "Name" : "Hello World", "Phone" : "Phone : 123-456-6789 ", "Region" : "New York", "Description" : "" ...

Is it possible to cache silverlight WCF service calls?

The service being called by the application is using WCF BinaryEncoding and requires 3 parameters. While I have experience with making similar calls using JavaScript Ajax stacks, I have not attempted it with Silverlight before. I am wondering if this is p ...

Error encountered: JSON data contains an unexpected character at line 1, column 2

One of my PHP scripts looks like this: $STL = array(); $filter = array(); $filter['sort_by'] = "date_added"; $filter['sale'] = "F"; $filter['per_page'] = "12"; $STL['filter'] = $filter; echo json_encode($STL); When ...

When using web2py, how does JavaScript determine when all LOAD() components have finished loading?

I am currently facing a challenge in web2py where I need to load multiple separate forms onto a single web page using the {{=LOAD(...)}} function. My main concern is how I can trigger a JavaScript function once all of these forms have completed loading i ...

Display the current count of selected radio buttons in real-time

I am working with radio buttons that are generated dynamically using a 2D array within a while loop. I want to display the number of radio buttons checked when one is clicked. Here are my radio buttons: $n=0; while($row=mysqli_fetch_row($rs)){?> <f ...

Tips on passing a variable into a controller using jQuery AJAX from the URL

Can you help me figure out how to pass an id to a function in the controller? I keep getting an error saying it cannot find the method in the controller. Here's my view: function Delete1(id) { if (confirm("Are you sure?")) { $. ...

Utilizing Angular Observables to Consume a REST API

Recently, I developed a REST API using Flask. However, when I tried to integrate it with my Angular web app, I encountered some errors. Despite following the steps outlined in the official documentation: https://angular.io/tutorial/toh-pt6 getBills(): voi ...

Tips for confirming if a file has finished downloading before exiting the web driver using Java Selenium

Trying to download a file with Java Selenium can be quite tricky. After clicking the download button, there is a delay in initiating and completing the download depending on the file size and internet speed. The problem arises when the next code is execut ...

How to process routes such as /search/:search(/filter1/:filter1)?

I want to process paths like the following: /search/:search /search/:search/filter1/:filter1 /search/:search/filter2/:filter2 /search/:search/filter1/:filter1/filter2/:filter2 How can I achieve this using restify or expressjs (or any other REST lib)? I ...

When the button is clicked, initiate the download of a file and include a parameter containing the desired value to be

If there is a change in the table on the index page triggered by a specific event, another file called excel.php can be used to generate an Excel sheet. To run the excel.php file and download the excel file while staying on the index page, a jQuery script ...

Obtain the raw JSON URL from the web

Is there a website that can provide me with a constant URL for my JSON code so that I can edit it and see the changes reflected live on the same link? Currently, when I try to edit JSON code on gist.github.com, the URL of the raw format changes. Any sugg ...

Popup text alert remains persistent in SeleniumPlus test on Internet Explorer

Currently, I am using a method called VerifyAndDismissAlert() in an automated test. try{ WebDriver WD = WebDriver(); Alert alert = WD.switchTo().alert(); alert.accept(); String alertText = alert.getText(); Pause(1); ...

The JSON java.sql.SQLException occurs when attempting to execute a Positioned Update that is not

In my attempts to utilize JSON in Java Web development, I encountered an issue when trying to transform a List into a JSONArray using the JSONArray.fromObject() method. The exception thrown is as follows: java.sql.SQLException: Positioned Update not suppo ...

The process of transforming a String response into an iterable entity

I'm currently working on an Android/Java app where I need to make a REST API call using the Volley library. Here's the code I have so far: RequestQueue queue = Volley.newRequestQueue(this); String url ="https://covid19datasl.herokuapp.co ...

Creating a Rails application that dynamically fills a table with data from a

Encountering an issue with Ruby on Rails. I have a "Host Model" that contains a method which has a longer runtime. class Host < ActiveRecord::Base def take-a-while # implement logic here end Attempting to access a page where this method ru ...

I would like to display an error message in close proximity to my form

The controller function is shown below. In the addinvoices function, a checking function is called. If the condition is true, the page will be redirected to a view page; otherwise, it will stay on the same page and show an error message. $this->loa ...

Automating the process of logging into Wordpress

I'm attempting to streamline the login process for www.wordpress.com Step1: First, click on the "Login" button located at the top right corner of the page. Step2: Next, click on the "Continue with Google" option on the Login page. However, I've ...