简体   繁体   中英

Get an alert when a form cant be submitted using ajax

I have a form for a user to request a day off, on my server side i have functionality to check if more than 3 people have asked for that same day off and if they have it wont let the user request that day. I want to display a pop up/alert when they cant request that day

This is in my method in my controller

if(results.size() >3)
{
   System.out.println("Too many people asked for that day off");
   return new ModelAndView("request");

}
else
{
    Request request = new Request();
    request.setDate(newDate);
    request.setNumDays(numDays);
    request.setReason(reason1);

    ModelAndView mv = new ModelAndView("successRequest");
    mv.addObject("request", request);

    requestService.save(request);
        return mv;
}

It return an empty form when there is more than 3 requests for that day but i also want it to have an alert message Ive tried to do it on my jsp page using ajax

$('#form').submit(function(e)
{   
     $.ajax({
     type:'POST',
     url:"/request",
     data:$(this).serialize(),
     error: function(){
      window.alert("Too many people have asked for that day off");
      console.log("Error");
     }
});     
});

AJAX is expecting JSON response not ModelAndView Object.

So First things to do is to return JSON Response using @ResponseBody instead of ModelAndView Object.

Then based on the flag value you can show the alert to user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM