Implementing reCAPTCHA in Spring MVC with Ajax

I've been attempting to implement Google reCAPTCHA service with Spring MVC, but I keep encountering this error in the 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)

Below are 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's 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'm struggling to pinpoint the issue.

Any guidance on fixing this error would be greatly appreciated!

Thank you

Answer №1

The RequestMapping for "/ajaxtest" does not match the URL provided in the Ajax call.

Ensure that you use "ajaxtest" instead of "ajaxtest.htm" when making the Ajax call.

You can find a helpful reference on integrating Spring MVC with reCaptcha by visiting this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process: Starting with the base class import { PageE ...

Updating JSON data in Node.js by adding a new object

I'm facing a situation where I have a JSON file acting as a database to manage users by adding, removing, and modifying them. Currently, I have the following code snippet: 'use strict'; const fs = require('fs'); let student = { ...

Repairing the toggle feature using a pair of buttons

I am looking to make changes to my code so that when a button is clicked twice, it reverts back to its original state. Additionally, is there a way to have neither gender button selected upon page load? If you want to see the code in action, follow this l ...

How to decode JSON data into a JavaScript array and retrieve specific values using index positioning

Upon receiving a json response via ajax, the code looks like this: echo json_encode($data); The corresponding ajax code is shown below: $.ajax({ url:"PaymentSlip/check", data:{val:val}, type: 'POST', succe ...

The expansion animation for the Nextjs/React accordion box did not work as expected when utilizing tailwindcss

I am currently working on creating an animation for a collapsible box (accordion). My goal is to have the child component initially hidden with display:none. When I hover over the parent component, the child should be revealed and the dimensions of the pa ...

javascript design pattern - achieving unexpected outcome

In the code snippet provided, the variable a is turning out to be undefined. Are you expecting it to display the parameter value passed in the parent function? function test(a) { return function(a) { console.log('a is : ' + a); // Ou ...

"How can I make a dropdown open and close when a button is clicked, but also close when clicking outside of it at the same

One button click opens a dropdown, and it also closes when clicked outside. toggleAllCategories() { this.setState({ isOpenAllCategories: !this.state.isOpenAllCategories }); } The issue arises when attempting to open and close the dropdown by clic ...

Fill out a Form in a separate Tab multiple times

I'm currently developing a straightforward form for distributing a newsletter: <form method="post" id="newsletter_form" action=""> <label for="subject">Newsletter Subject:</label><br/> <input type="text" nam ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

Comparing the Round-trip Time of AJAX versus Web Sockets

Can one expect a variance in round-trip time when using web sockets (message) versus a standard HTTP GET for sending information to the server and receiving a response? Assuming the web socket is already connected and DNS has been resolved. From my unders ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

Can the execution of a jQuery Timeout function be halted if a user navigates away from the page?

Implementing a timer in a view with jQuery: var timer, myDiv = $('#mydiv'); $(document).on('mousemove', function(ev) { var _self = $(ev.target); clearTimeout(timer); if (_self.attr('id') === 'mydiv' || ...

In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary? var arr = '1/1/22'; arr = NTE ...

Is it possible for me to utilize pure JavaScript for loading JSON data?

I am interested in dynamically creating a Google Map by loading data through AJAX. To achieve this, I am using a JSON object that mimics the structure of the GM API to construct the map and jQuery for AJAX loading. For example: "object": { "div": "ma ...

The Next.js error message reads: 'Issue with setting properties on undefined entity (specifically 'hook')'

This issue seems to occur either when the app is launched or when updating the Redux state. It may not show up consistently for every state update, but for some reason it persists throughout the entire app. What I have attempted so far: Removing node mod ...

Requesting PayPal for an HTTPS transaction

When attempting to call the Express Checkout Paypal API using $http.get(AngularJS), I encountered error 81002(Method Specified is not Supported). However, when I tried calling the API using the search bar in Google Chrome, I was able to retrieve the token ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Is it possible to move the res.send() outside of the function in node.js?

I currently have the following code: var server = http.createServer(function(req,res){ res.writeHead(200,{'Content-Type': 'text/html; charset=utf-8'}); var oo = require('/test.js'); oo(connection, function (e, res ...

Issue encountered while attempting to save a value in localStorage

I am encountering an issue while trying to save and read the value of a button in the panel. The error message I receive is - Unable to set property 'adl' of undefined or null reference. This is my first time working with localStorage, so I' ...