Vignesh_E
Vignesh_E

Reputation: 167

Pass value from AJAX to Controller using Spring MVC

This is html code

  <ul id="myUL">
    <c:forEach var="userBean" items="${list}">   
    <li id="username"><a href="#">${userBean.username}</a></li>
    </c:forEach>  
    </ul>
<div class="card">
<p>${userBean.phoneno}</p>
<p>${userBean.Address}</p>
</div>

This is AJAX

<script>
  $("#myUL").click(function(){
      var username=$('#username').val();
      $.ajax({
            url: "details",
            type: 'GET',
            data: {username:username},
            success: function(data){
                   $("#card").html(data);
         }

      });
  });
  </script>

This is Controller code

@RequestMapping(value="details", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView details(@RequestParam UserBean userBean, HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView view = new ModelAndView();
        String username=userBean.getUsername();
        if(retrieveService.getdetail(userBean)!= null)
        {
            view.setViewName("welcomes");
        }
        return null;

    }

I don't know how to pass a value from AJAX to the controller. This is sample output

Name                  Details
john                  john
smith                 phoneno. 324242
                      Address:xyz

If I click Name i.e <li> tag. it will show Details from MySQL to JSP

Upvotes: 1

Views: 3963

Answers (3)

Amar Prakash Pandey
Amar Prakash Pandey

Reputation: 1336

Change your JavaScript Code to:

<script>
    $("#myUL").click(function(){
        var username=$('#username').val();
        $.ajax({
            url: "details",
            type: 'POST',
            data: {username:username},
            success: function(data) {
                         $("#card").html(data);
            }
        });
    });
</script>

And Change your Controller code to:

@PostMapping(value = "details")
    public ModelAndView details(@RequestBody UserBean userBean, HttpServletRequest request,
            HttpServletResponse response) {

        ModelAndView view = new ModelAndView();
        String username = userBean.getUsername();

        if (retrieveService.getdetail(userBean) != null) {
            view.setViewName("welcomes");
        }

    return view;
}

Upvotes: 1

nicce
nicce

Reputation: 1

You should also use @RequestBody instead of @RequestParam since it's a POST and you send the data in the body and not in the url.

Upvotes: 0

dnny
dnny

Reputation: 136

You are sending GET request to controller which receives POST request?

Upvotes: 0

Related Questions