Using reCAPTCHA with Ajax in Spring MVC - javascript

I am trying to use google reCAPTCHA service with spring MVC.But I am getting this error on console:
http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=ededeā€¦nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrnRc_ISQh&recaptcha_response_field=1404 Failed to load resource: the server responded with a status of 400 (Bad Request)
Here is My AJAX JavaScript Codes:
$(document).on("click","button#save",function(){
var name=$("input#name").val();
var surname=$("input#surname").val();
var phone=$("input#phone").val();
var recaptcha_challenge_field=$("#recaptcha_challenge_field").val();
var recaptcha_response_field=$("#recaptcha_response_field").val();
var error=0;
if(name==""){
$("label#stateName").html("First Name field must be filled!");
error=1;
}
if(surname==""){
$("label#stateSurName").html("Last Name field must be filled!");
error=1;
}
if(error==0) {
$("div#addResult").html("<img src=\"resources/images/loading.gif\" style=\"max-width:50px;max-height:50px;margin-left:250px;\"/>");
setTimeout(
function()
{
$.ajax({
url:"ajaxtest.htm",
data:{name:name,
surname:surname,
phone:phone,
recaptcha_challenge_field:recaptcha_challenge_field,
recaptcha_response_field:recaptcha_response_field},
success:function(response){
$("div#addResult").html(response);
}
});
}, 2000);
}
});
Here My Controller Method:
#RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
public #ResponseBody String ajaxCRUDPerson(
#ModelAttribute Person person,
ModelMap model,
#RequestParam(value="id") String id,
#RequestParam(value="name") String name,
#RequestParam(value="surname") String surname,
#RequestParam(value="phone") String phoneNumber,
#RequestParam("recaptcha_challenge_field") String challangeField,
#RequestParam("recaptcha_response_field") String responseField,
ServletRequest servletRequest) {
String remoteAddress = servletRequest.getRemoteAddr();
ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(remoteAddress,challangeField, responseField);
String result = "";
if(reCaptchaResponse.isValid()){
if(StringUtils.hasText(person.getId())) {
person.setName(name);
person.setSurname(surname);
person.setPhoneNumber(phoneNumber);
personService.updatePerson(person);
result+="The person has been updated successfully! "+person.getName();
} else {
person.setName(name);
person.setSurname(surname);
person.setPhoneNumber(phoneNumber);
personService.addPerson(person);
result+="The person has been inserted successfully!";
}
model.addAttribute("personList", personService.listPerson());
return result;
}else{
return "Invalid answer!";
}
}
I couldnt understand where is wrong.
How Can I fix this error!
Thanks

RequestMapping "/ajaxtest" is not matching with the url passed in the Ajax call.
Use "ajaxtest" instead of "ajaxtest.htm" in the Ajax call.
Reference: Spring MVC based reCaptch with live demo http://www.srccodes.com/p/article/33/integrate-free-anti-bot-service-recaptcha-with-spring-mvc-application

Related

How to call spring service (RequestParam ) from in java script function (Error 400: Required String parameter 'flag' is not present)

I want to call a spring service from script function ,but i am unable to call my service for below code. Can you please suggest me i am doing correct or wrong.
Controller class:
#RequestMapping(value = "/download", method = { RequestMethod.GET, RequestMethod.POST })
#ResponseStatus(value = HttpStatus.OK)
public String downloadFile(#RequestParam String flag, HttpServletResponse response) throws IOException {
return flag;
}
<script>
function downloadPdf(flag) {
if (flag == 'PRINT') {
redirectUrl = "download.htm/flag=" + flag;
var myWindow = window.open(redirectUrl , '',
'width=200,height=100');
myWindow.focus();
myWindow.print();
}
}
</script>
When run my code i facing issue like
Error 400: Required String parameter 'flag' is not present
You can mark the #RequestParam as required=false (default value is true).
If you are using a query parameter on the URL, the URL should be something like download.html?flag=value not download.html/flag=value. What you have on the example is a weird mix between #RequestParam and #PathVariable.

JQuery/AJAX call is not hitting Spring MVC controller

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;
}
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.
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"

AJAX call returning 404 error due to incorrect content type

AJAX call returns:
HTTP Status 404 -
/mycustomproject/en/WEB-INF/views/desktop/register/region.jsp
Incidentally, this is the same URL that I am using to make the Ajax call.
$( "#address\\.country_del" ).change(function() {
alert( "Handler for .change() called." );
$.ajax({
url: '/register/region',
data:
{
country: $("#address\\.country_del").val()
},
type: "POST",
}).done(function (data){});
});
Controller:
#RequestMapping(method = RequestMethod.POST, value = "/region")
public List<RegionData> getRegion(#RequestParam(value = "country") final String country)
{
final String isocode = country;
final List<RegionData> regions = i18NFacade.getRegionsForCountryIso(isocode);
return regions;
}
My request and response as seen on browser:
I think the problem is with the content type of response ?!
The issue here is your view resolver as you can see that your response from your controller class is resolved to jsp
HTTP Status 404 - /mycustomproject/en/WEB-INF/views/desktop/register/region.jsp
So you need to let your method in your controller know that it needs to return a JSON
You can do that annotating the method by #ResponseBody
#ResponseBody, what it does is that it return object as the body, in the format specified in produces="application/json".
#RequestMapping(method = RequestMethod.POST, value = "/region" ,produces="application/json")
#ResponseBody
public List<RegionData> getRegion(#RequestParam(value = "country") final String country)
{
final String isocode = country;
final List<RegionData> regions = i18NFacade.getRegionsForCountryIso(isocode);
return regions;
}

jQuery Ajax request with error 404 (not found) but it works

I'm sending a jQuery AJAX request to the server, but the browser's console tells me that the page is not found. Still, my Spring MVC signature mapping the requested URL is executed, and yet the done part of the AJAX function is not.
Here is the relevant code:
Javascript:
var content = $(data).filter("#wrapper-email-content");
$.ajax({
url : '/sendEmail',
type : 'POST',
data : {
content: content.html()
}
}).done(function(){
console.log("Finished")
});
Spring MVC Signature:
#RequestMapping(value = "/sendEmail", method = RequestMethod.POST)
public void sendEmail(
HttpServletRequest request, String content) {
UserTO user = (UserTO) request.getSession().getAttribute("USER");
String email = user.getEmail();
String title = "Your order";
Email.sendEmail(title, email, content, null, null, null);
}
So, in the code, the email is sent, meaning that sendEmail method is executed, but I still get the Error 404: not found from the AJAX request, and "Finished" is not printed in the console.
What am I doing wrong?
#RequestMapping(value = "/sendEmail",headers="Accept=application/json", method = RequestMethod.POST)
public Map<String,String> sendEmail(
HttpServletRequest request, #RequestBody String content) {
Map<String,String> statusMap=new HashMap<String,String>();
UserTO user = (UserTO) request.getSession().getAttribute("USER");
String email = user.getEmail();
String title = "Your order";
Email.sendEmail(title, email, content, null, null, null);
statusMap.put("status","Mail sent successfully");
return statusMap;
}
The better solution is annotating your method with
#ResponseStatus(value = HttpStatus.OK)
see answer https://stackoverflow.com/a/12839817/954602 for the example.
EDIT: see solution posted for What to return if Spring MVC controller method doesn't return value?
Not familiar with MVC Spring, but you probably need to return a success status code yourself:
public String sendEmail(
HttpServletRequest request, #RequestBody String content) {
UserTO user = (UserTO) request.getSession().getAttribute("USER");
String email = user.getEmail();
String title = "Your order";
Email.sendEmail(title, email, content, null, null, null);
return new ResponseEntity<String>(json,HttpStatus.OK);
}

Ajax call always return error in springMVC

Ajax call :
$.ajax({
type:'post',
url:'https://hybris.local:9002/store/verify?productCodePost='+productid,
data : {notifyemail : notifyemail},
dataType : "text",
success : successmethod,
error : function(data, status) {
//alert("Error "+status);
$('#showbecomepartnerMessage').show();
}
});
alert("test values are"+notifyemail);
document.getElementById('notifyemail').value='';
}
function successmethod(data) {
if (data != null) {
alert('Success');
$('#showemailMessage').show();
} else {
alert('Error');
}
}
Controller:
#RequestMapping(value = "/verify", method = RequestMethod.POST, produces = "application/json")
public String verifyEmail(#RequestParam("productCodePost") final String code, final Model model,
#Valid final AddToCartForm form)
{
System.out.println("Inside Verify method");
final String email = form.getNotifyemail();
System.out.println("Email is " + email);
System.out.println("Product code is== " + code);
final Boolean status = true;
if (email != null)
{
System.out.println("Email id is" + email);
notifyStockEmail(email, code);
}
if (status.booleanValue())
{
System.out.println("value of Boolean " + status.booleanValue());
//return "success";
model.addAttribute("success", "success");
}
else
{
//return "fail";
model.addAttribute("error", "error");
}
return "success";
}
In the above code i am doing a ajax call and calling a controller '/verify' and from controller i am returning a boolean value as true but everytime error method is executed in the jsp instead of success method.So how can i call success method by passing true value from controller as above.Any help would be appreciated.
please, try this:
#RequestMapping(value = "/verify", method = RequestMethod.POST)
public #ResponseBody String verifyEmail(#RequestParam("productCodePost") final String code) {
//do what you want and return your status
return "OK";
}
And you ajax call should be something like:
$.ajax({
type:'post',
url:'https://hybris.local:9002/store/verify?productCodePost='+productid
}).success(function(data) {
successmethod(data);
});
Despite your assertion, you are not returning a boolean value. You are putting a some String attributes named 'success' and 'error' in the Model and forwarding to a view named "success" and which or may not exist.
If you simply want the boolean value true|false written to the response stream then you can do this as below.
Add the #ResponseBody annotation:
#RequestMapping(value = "/verify", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody boolean verifyEmail(#RequestParam("productCodePost") final String code, final Model model,
#Valid final AddToCartForm form){
boolean status = false;
//check and set status.
return status;
}
See:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
This annotation can be put on a method and indicates that the return
type should be written straight to the HTTP response body (and not
placed in a Model, or interpreted as a view name)

Categories

Resources