Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call controller method from JSP button in Spring MVC

I would like to call a controller method using a button on a JSP page in Spring MVC, but I would like it to stay on a current page, don't reload it or anything, simply call a method. I found it difficult. My button is on cars.jsp page. In order to stay on this page I have to do something like this:

@RequestMapping(value="/start")
public String startCheckingStatus(Model model){
    System.out.println("start");
    model.addAttribute("cars", this.carService.getCars());
    return "car\\cars";
}

button:

 <a href="<spring:url value="/cars/start"/>">Start</a>

But this is not a good solution because my page is actually reloaded. Can I just call controller method without any refreshing, redirecting or anything? When I remove return type like so:

@RequestMapping(value="/start")
public void startCheckingStatus(Model model){
    System.out.println("start");
}

I got 404.

like image 984
jarosik Avatar asked Oct 30 '22 11:10

jarosik


1 Answers

Add an onclick event on your button and call the following code from your javascript:

 $("#yourButtonId").click(function(){
    $.ajax({
        url : 'start',
        method : 'GET',
        async : false,
        complete : function(data) {
            console.log(data.responseText);
        }
    });

});

If you want to wait for the result of the call then keep async : false otherwise remove it.

like image 179
Zeeshan Avatar answered Nov 12 '22 23:11

Zeeshan