I am validating a form using jquery.validate.js
and I need to identify duplicate entries, for this I am using custom method i.e:
jQuery.validator.addMethod("uniqueName", function(name, element) {
var response;
$.ajax({
type: "POST",
dataType : "json",
url:"${pageContext.request.contextPath}/company/getDuplicate",
data:"name="+name,
async:false,
success:function(data){
response = data;
},
error: function (data) {
alert(request.responseText);
}
});
}, "Name is Already Taken");
in rules section:
rules : {
name : {
required : true,
uniqueName : true
}
},
errorElement : "span",
messages : {
name : {
required : "Name Is Required"
}
}
this is my JSP code:
<label>Name:</lable>
<form:input path="name"></form:input>
It's hitting for specified url but Json sending null value to the method
this is my controller method:
@RequestMapping(value = "/company/getDuplicate", method = RequestMethod.POST, headers = "Accept=*/*")
public @ResponseBody void getTitleList(HttpServletRequest request, HttpServletResponse response) {
JSONObject json = new JSONObject();
String data = ((String)json.get("name"));
List<Company> matched = companyService.getDuplicate(data);
if (matched != null && !"".equals(matched)) {
json.put("name", "present");
System.out.flush();
}
else {
json.put("name", "notPresent");
System.out.flush();
}
}
what I want is:
Please help me with this issues. Thanks in advance.
Modify your code as below:
$.ajax({
type: "POST",
dataType : "json",
url:"${pageContext.request.contextPath}/company/getDuplicate",
data:{"name":name},
async:false,
success:function(data) {
response = data;
},
error: function (data) {
alert(request.responseText);
}
});
and Modify your controller handler as
Notice the commented first two lines and addtional @RequestParam(value="name") String name
in method signature
@RequestMapping(value = "/company/getDuplicate", method = RequestMethod.POST, headers = "Accept=*/*")
public @ResponseBody void getTitleList(@RequestParam(value="name") String name,HttpServletRequest request, HttpServletResponse response) {
//JSONObject json = new JSONObject();
//String data = ((String)json.get("name"));
List<Company> matched = companyService.getDuplicate(name);
if (matched != null && !"".equals(matched)) {
json.put("name", "present");
System.out.flush();
} else {
json.put("name", "notPresent");
System.out.flush();
}
}