Reputation: 119
I am trying to verify username and other fields while creating a change password page.The problem is AJAX call in Jquery script is not hitting my controller.i tried giving hard coded path also in url field of the ajax request. Below is my Script
this checkUname function is triggering on onblur event from one of the input field.
<script type="text/javascript">
function checkUname()
{
// get the form values
var uName = $('#username').val();
var secQues = $('#secQues').val();
var secAns = $('#secAns').val();
var dataObject = JSON.stringify({
'uName' : uName,
'secQues': secQues,
'secAns' : secAns
});
$.ajax({
url:"validateCredentials.do" ,
type: "POST" ,
data: dataObject ,
contentType: "application/json; charset=utf-8" ,
dataType : 'json' ,
success: function(response)
{
alert(response);
} ,
error: function()
{
alert('Error fetching record.... Sorry..');
}
});
}
</script>
This is my MVC controller
@Controller
public class ArsController
{
@RequestMapping(value="validateCredentials.do", method = RequestMethod.POST)
public String changePass(@RequestParam("uName") String uName ,@RequestParam("secQues")String secQues,
@RequestParam("secAns") String secAns)
{
System.out.println("AJAX request");
Users dummyUSer = null;
String msg = null;
try
{
dummyUSer = servObj.findUser(uName);
}
catch (ArsException e)
{
System.out.println("error occurred while validating user data during password change");
e.printStackTrace();
}
if(dummyUSer == null)
{
msg = "No user exists with this username";
}
else
{
if(!secQues.equals(dummyUSer.getSecQues()))
{
msg = "Security question is not correct";
}
else
{
if(!secAns.equals(dummyUSer.getSecAns()))
{
msg = "Security answer does not match";
}
}
}
return msg;
}
Upvotes: 6
Views: 1426
Reputation: 75
try remove content-type and data-type. You are not sending a json that should be parsed in a object, you are sending controller's parameters. The way to do that is using an object in the Ajax 's data (as you did) but without the content-type or data-type that saying "I'm sending one json parameter"
Upvotes: 0
Reputation: 2181
Instead of using RequestParam in controller, you should use String. Because when we are posting JSON data it will not come as individual parameters in Request, instead it will be received as String in your controller. Once you get the String convert it to JSON object and then get your values accordingly.
Upvotes: 2