Canceling a window in JSP and navigating back to the previous page using JavaScript

Here is my Java class controller:

    public class Controller extends HttpServlet {

    private Chooser chooser = Chooser.INSTANCE;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    private void processRequest(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String page = chooser.chooseCommand(req.getParameter("command")).execute(req, resp);
            req.getRequestDispatcher(page).forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
}

Now, let's look at the ENUM class that selects a page:

public enum Chooser {

    INSTANCE;

    private Map<String, ICommand> commandMap = new HashMap<>();

    private Chooser() {

        // commands for profession
        commandMap.put("professions", new ProfessionCommand());
        commandMap.put("addProfession", new AddProfessionCommand());
        commandMap.put("saveProfession", new SaveProfessionCommand());
        commandMap.put("deleteProfession", new DeleteProfessionCommand());
        commandMap.put("editProfession", new EditProfessionCommand());

        public ICommand chooseCommand(String command) {
        return commandMap.get(command);
    }

}

There's also an interface, ICommand:

public interface ICommand {

    String execute(HttpServletRequest request, HttpServletResponse resp);

}

Now, let's check out the DeleteProfessionCommand class:

public class DeleteProfessionCommand implements ICommand {

    private ApplicantDBProvider provider = ApplicantDBProvider.INSTANCE;

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse resp) {

        try {
            Long professionId = Long.parseLong(request.getParameter("id"));
            provider.deleteProfession(professionId);
        } catch (Exception e) {
            request.setAttribute("error", e);
            return "pages/error.jsp";
        }

        return "controller?command=professions";
    }
}

In my JSP file, I have an anchor tag like this to delete a row:

<a href="controller?command=deleteProfession&id=${profession.getId()}">Delete</a>

My question now is, how can I display an alert message when I click on delete with options to confirm or cancel. I am still learning Java and would appreciate any help. Thank you!

Answer №1

To implement this functionality with javascript, modify the anchor tag for Delete in your jsp file.

<a href="controller?command=deleteProfession&id=${profession.getId()}">Delete</a>

Update the anchor tag as follows:

<a class="deleteAnchor" data-command="deleteProfession" data-id="${profession.getId()}" href="javascript:void(0);">Delete</a>

Then, include the following script at the end of your jsp file:

<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript">
$('.deleteAnchor').on('click', function(){
    var result = confirm('Are you sure to delete?');
    if(result) {
        //Code to delete using AJAX
        $.ajax({
            url: 'controller',
            data: {'command' : $(this).data('command'), 'id' : $(this).data('id')},
            success: function() {
                //Handle success response here
            }
        });
    } else {
        //Do nothing if user cancels
    }
});
</script>

You may also consider using bootbox for a more visually appealing confirmation dialog.

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

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

Java Loop executing just a single iteration

Currently, I am in the process of creating a code guessing game. If you enter an invalid input, such as '333', the game will request you to change your guess. Surprisingly, this feature only applies to the first guess. For guesses 2 through 6, th ...

repeating the identical content in the same setting

I am encountering an issue with jquery as I have 2 different sets of icons, each of which I want to do the same thing: My primary codes are <ul> <li> <a href=""> <i class="fa fa-facebook"></i> ...

How can I incorporate a standalone Vuetify component into my Nuxt.js project?

Using Vuetify with nuxt.js specifically for the dashboard layout - how can I achieve this in my nuxt.config.js file? modules: [ //['nuxt-leaflet', { /* module options */}], 'bootstrap-vue/nuxt', '@nuxtjs/ax ...

Sending Dual Parameters to PHP File Using AJAX

Currently, I am facing an issue where I can successfully pass one value to a Bootstrap modal via AJAX, but my code stops working when I try to pass a second value. JavaScript function claimOrder(str, stre){ if (str=="") { document.getElementById("txtH"). ...

Is it possible to send arguments to the functions executed by "jQuery then"?

Check out the complete code here: http://jsfiddle.net/BurFz/ http://jsbin.com/dagequha/1/edit?js,console /** * executed function chain */ func1('arg1').then(func2).then(func3).then(function () { console.log('execution comp ...

Integrate PEM certificate into an Http Request with AngularJS/NodeJS

Currently, I am working on an application that requires retrieving data from a REST endpoint within an encrypted network. Accessing this data is only possible by physically being present (which is currently not an option) or using a PEM certificate provide ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

Why does Chrome keep retrieving an outdated JavaScript file?

Lately, I've been facing a frustrating issue that I just can't seem to figure out. Every now and then, when I update the JavaScript or CSS files for my website hosted on Siteground, Chrome simply refuses to acknowledge the changes. While other br ...

Having issues with adding elements to an array object in JavaScript

I've got some HTML code that looks like this: HTML: <INPUT TYPE=CHECKBOX NAME="clcik" onClick="add('1234','blah')" /> <input type="hidden" id="project" value="" /> JS: function add(obj1 , obj2){ var jsonAr ...

There has been an error during the jHipster production build process. The task "yarn run webpack:prod" has failed to execute

After creating a monolithic application using jHipster 4.9.0, I attempted to run mvn -Pprod package only to encounter a build failure with the subsequent errors displayed. [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.6:yarn ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

How can I achieve a stylish scrolling header similar to a Google Blog for my website?

Google's blog features a unique header design - as you scroll down, the gray bar in the header moves up until it locks at the top of the screen. While CSS's position:fixed can achieve a similar effect, Google seems to have used a combination of p ...

How can I leverage the knowledge gained from a class to achieve my desired outcomes?

I'm currently working on a project where I need to read a file and store its contents in an ArrayList. I plan to use the split method from the String class to format the tokens into another ArrayList. However, I'm facing an issue with my while lo ...

Using AngularJS to invoke the ng-required directive and trigger a function

Is it possible to make the required value dependent on a function? Something similar to this? I need to achieve this in order to dynamically change the required attribute for form inputs... HTML: Name: <input type="text" ng-model="user.name" ng-r ...

Ways to identify which arrays within an object contain an element

This question is unique as it pertains to objects of arrays rather than arrays of objects. I am working with a data structure like the one below and my goal is to determine if any of the arrays inside the object have values. What I'm looking for is a ...

The x-axis values in Amchart are transitioning rather than shifting

I'm facing an issue with my x-axis values as I'm using real-time amcharts. The x-axis values change every 3 seconds, but instead of smoothly moving, they abruptly change to the next value. I would like it to slide smoothly like this example: htt ...