triggering controller on click event in JSP

Using a spring web application, I need to call a controller in a java file from a JSP file using an ajax function. How can I achieve this?

<p class="bottom-slide-corners">
                            <a class="billing" href="#Billing"><spring:message code="billing_area" /></a>
                        </p>


$('.billing').on('click', function(event) {
            clearSliderInterval();
            var $this = $(this);
            var $linkToFind = $($this.attr("href") + "_billing");
            var $slidesToFind = $("." + $this.attr("href").replace("#", "") + "_slide");

            if($this.parent().parent().siblings('.current-arrow').find('img').is(":visible")) {
                $this.parent().parent().siblings('.current-arrow').find('img:visible').slideUp();
                $('.Background').slideUp(function() {
                    $(".learn_more").hide();
                }).removeClass("open");
                return false;
            }

            if($window.width() <= 767) {
                $('#dashboard-mobile-banner, #header-bg, #footer-container, .container-slider').slideUp();

                var categoryClass = $linkToFind.attr('id').replace("learnMore", "slide");
                $('.courseDashboard').removeClass().addClass("courseDashboard Background " + categoryClass);
                $('body, html').animate({ scrollTop: 0 }, "fast");
            }

            if($('.learn_more').is(":visible")) {
                $('.Background').slideUp(function() {
                    $('.learn_more').hide();
                    $linkToFind.show();
                    $('.Background').slideDown();
                });
            } else {
                $linkToFind.show();
                $('.Background').slideDown(function() {
                    if ($window.width() <= 767) {
                        var slider = $("#" + $linkToFind.attr('id') + " .thumbview").bxSlider({
                            slideWidth: 300,
                            pager: false
                        });
                        $('.close-panel:visible').on('click', function(e) {
                            slider.destroySlider();
                        });
                    }
                }).addClass("open");
            }

            $('.current-arrow img:visible').slideUp();
            $slidesToFind.find('.current-arrow img').slideDown();
            return false;
        });

When the above content is clicked, I want to call the following controller in a .java file. How can I write the code to accomplish this in a JSP file?

    @RequestMapping(value = "/billing", method = RequestMethod.POST)
    public String Billing(@RequestParam Long caseId,
            @RequestParam Long noteID, HttpServletRequest request)  throws Exception {
        try{

----------
            logger.debug("success ");
        return "success";
        } catch (Exception e) {
            logger.error(e,e);
            throw e;
        }}

Answer №1

If you follow these steps, it is guaranteed to work flawlessly :)

(".billing").on('click',function(){
    $.ajax({url:"/billing", success: function(result){

    }});
}) 

To return the success string in a map provided by JSONObject, make sure your key is "result" and your String value is "success". In your controller, include code like this:

`JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("result", "success");
String myResult= jsonObject1.toString();
response.getWriter().write(myResult);`           

In addition to adding resp.getWriter(), ensure that you have a response Object called HttpServletResponse resp in your method public String Billing method just like you have already added HttpServletRequest request. Do not include a return statement in the Controller and specify the controller method as void. These steps will definitely lead to success. Let me know if you need any further assistance! :)

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

Utilize HTML to place text above an image within a TextView

While working with a list of Strings that I add to TextViews individually, I encounter an issue with displaying images alongside the text. The HTML format allows me to include images within the text, but currently, the image appears below the text instea ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...

Unique ActionBar design for my NativeScript-Vue application

I'm currently working on customizing the ActionBar for my nativescript-vue app. I have implemented FlexBoxLayout within the ActionBar, but I am facing an issue where the icon and title of the bar are not aligning to the left as intended; instead, they ...

Tips for sending data from Jade to a Node.js endpoint function

I am unfamiliar with Express and I am trying to figure out how to pass the user's username from a Jade file to an endpoint function in my JavaScript file. Below is the code for the endpoint function in index.js: router.get('/userdetail', fu ...

Angular parent scope does not reflect changes when a directive updates the shared scope variable

My directive is designed to validate and modify a specific binded value before triggering the button action. However, I am facing an issue where any updates made to the directive value are not being reflected in the parent scope. Even though I have used (= ...

Having trouble with the locality function in Google Places v3 API autocomplete?

After successfully using the code below for about a week, I returned to work on it and found that it was no longer functioning properly. My goal is to only display localities. According to Google's documentation, "locality" is the correct option for a ...

What is the most effective way to ensure that a child component only executes when a link is clicked on the Vue component?

There are two components in my code The first component, which is the parent component, looks like this : <template> <ul class="list-group"> <li v-for="item in invoices" class="list-group-item"> <div class="ro ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Jasmine spies falsely report the calling of functions when they have not actually been called

Below is the code snippet I am currently working with: $scope.deleteJob = function(job) { SandboxService.deleteJob(job.id).then(res => { if (res.status == 200) { ngToast.success(); $scope.refreshApps(); } ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...

Ways to set the className prop for all components automatically without having to specify it repeatedly

One challenge I face is dealing with code duplication whenever I create a new component. Is there a way to pass the className property between components without having to explicitly define it every time a new component is created? For example, when I cr ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

What is the process for creating a button click listener event in Kotlin or JavaScript?

While working in IntelliJ IDEA, I have created a button in my HTML file with an ID. My goal is to change the header tag to say "button clicked" using Kotlin. After searching through kotlinlang.org and other resources, I am struggling to find a simple refe ...

Guide to dynamically updating the href of an SVG Image in Angular HTML

I am currently iterating through a list of employee objects, each containing an image URL that I need to incorporate into an SVG - Image element. <div *ngFor ="emp of employees"> <defs> <pattern id = "attachedImage" height ...

Utilize GSON to encode a collection of objects in a map and ensure the preservation of type

In my coding project, I have defined a class as follows: public class MyClass { private final Map<Property, Object> properties; } The type Property is actually an enum. Imagine that the properties attribute contains two elements: one with a v ...

The efficiency of Ajax JSON timeouts needs improvement

Currently, I'm in the process of developing an interactive map with specific functionalities. Essentially, the user will click on a year (stored as var currentyear) and then select a country (its name stored as var thenameonly). Subsequently, an AJAX ...

Looking to find and emphasize specific words using Java?

Is there a way to search for specific words on a webpage similar to using ctrl+f? How can I search and highlight a particular word on a webpage using Java and Selenium? For instance, I want to find the word "test" on this webpage: I attempted to combine s ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

Is it possible to trigger an event for only one connected client instead of broadcasting it to all clients using socket.io?

I am seeking a way to send an event to just one connected client, rather than broadcasting it to all clients using io.emit(). ...