Sunday, 1 May 2016

How to make Ajax request from Anchor tag to a Spring MVC controller through JQuery

Add the below dependency in pom.xml

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>

Add the below anchor link in the html or jsp page

 <a  name="check" id="check">Check Status</a>

Add the below script in .js file, be careful while providing the request attributes with double quotes

$("a#check").click(function(e) {
var requestdata={"TravelCode":"C001","TravelPackageNo": 100};
$.ajax({
"url": "check-status",
"type": "POST",
"contentType": "application/json",
"data": requestdata,
"global": true,
"complete": function(jqXHR, textStatus) {
},
"error": function(jqXHR, textStatus, errorThrown) {
$().endLoading();
}
});
});

Use the below code in the spring controller, the value provided should the same as given in the url attribute of the ajax request

@RequestMapping(value = "/check-status", method = RequestMethod.POST)
public @ResponseBody String checkStatus(@RequestBody TravelViewVo travelViewVo,
Model m, HttpServletRequest request) {

}

Class TravelViewVo {
 private String TravelCode;
private int  TravelPackageNo;

// set & get methods
}

No comments:

Post a Comment