Failure to execute after Ajax success

Currently working on a login page using Spring MVC on the server side and JS/Ajax on the client side. I'm facing an issue where the server code executes but does not return anything.

<script type="text/javascript">
    $(function() {
        $(".loguser").click(function() {
            var user = $("#login").val();
            var pass = $("#pass").val();            
            $.ajax({
                method: "POST",
                url : "${prefix}loginUser",
                data : "username=" + user + "&password=" + pass,
                dataType : "json",
                success: function(data){
                    if (data.res == "YES") alert("ok");
                    else alert("NOPE");
                }

            });
        })
    })
</script>
    <table id="userData" class="center">

                    <tr id="usernametr">
                        <th><label for="user">Nombre de usuario: </label></th>
                        <th><input id="login" type="text" name="login" value=""
                            placeholder="Name" required /></th>
                    </tr>
                    <tr>
                        <th><br /></th>
                    </tr>
                    <tr>
                        <th><label for="pass">Clave de usuario: </label></th>
                        <th><input id="pass" type="password" name="pass" value=""
                            placeholder="Password" required /></th>
                    </tr>

                    <tr>                        
                        <th><button class="loguser">Acceder</button></th>
                        <th><input type="button" name="lost"
                            value="He perdido mi clave" /></th>
                    </tr>
                </table>

HomeController.java:

@RequestMapping(value = "/loginUser")
    @ResponseBody
    @Transactional
    public String loginUser(@RequestParam("username") String username,
            @RequestParam("password") String pass, HttpServletRequest request, Model model) {
        logger.info("Trying to log in {} {}", username, pass);
        if (username.length() > 3) {
            logger.info("ok");
            return new String("[\"res\": \"YES\"]");
        } else {
            logger.warn("nope");
            return new String("[\"res\": \"NOPE\"]");
        }
    }

Also tried returning EntityResponse, but no changes were observed. The Spring console prints the logger info or warn statements, but Firefox's JavaScript console does not show any output.

Answer №1

Ensure to include the Requestmethod in your controller as shown below:

@RequestMapping(value = "/loginUser", method = RequestMethod.POST)

Make sure to return JSON values within curly braces { }.

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

Utilizing Ajax to make JSON requests using jQuery

I could really use some assistance here. I have a JSON file and I am attempting to retrieve only one image file by specifying its position, like the first one, for example. Is this achievable? I have experimented with various methods but it seems like some ...

How to Send Javascript DOM Value to Inner HTML

I am trying to extract a value from a hidden element ID and set it as the inner HTML for another element ID. Below is my code: <script> function replaceText(){ var x=document.getElementById("mainTitle1").textContent; document.getElementById("mainTi ...

What could be causing the custom aside or slide panel to not slide properly when using Angular Strap?

I recently tried creating a slide panel and came across the Angular Strap library. After studying the documentation, I attempted to implement the slide panel using this library. However, I encountered an issue where my side panel did not slide as demonst ...

"Upon clicking the button, the parameters passed will be in the form of a

Can someone help me figure out how to pass the datatable object as parameters to a controller in Laravel using the post method? I've tried but it's not working. Here is the code I have attempted: Datatable Object Array ( [draw] => 1 [co ...

Utilizing jQuery and CSS to make an entire div clickable, and activate an 'a' tag hover state upon hovering

Looking to create a clickable link for the .wrapper div that directs users to the location of a.icon. Want the .wrapper div to activate the a.icon:hover state when hovered over, not just when hovering over the icon itself. Any assistance would be highly a ...

Auto language-switch on page load

Wondering if using jQuery is the best approach to create a single French page on my predominantly English website. I want it to work across multiple browsers on pageload, currently using HTML replace. jQuery(function($) { $("body").children().each(funct ...

When attempting to display the details of each restaurant on my detail page, I encountered the error "Cannot read property 'name_restaurant' of undefined."

I have set up dynamic routing for a ProductDetail page, where each restaurant has its own details that should be displayed. The routing is functional, but I am facing difficulty in retrieving data from Firestore using the restaurant's ID. PS: Althoug ...

Canceling a request on timeout using Ajax/jQuery

Beginner - Inquiry - Issue at hand: In scenarios where there are lingering open connections not closed by XMLHttprequest, the goal is to terminate them. Within a javascript file handling Ajax calls, the objective is to initiate a timer for each call and ...

When I make a post request, I receive a response in the form of an HTTPS link, but it is not redirected to

I'm making a post request and receiving the response as follows: " [Symbol(Response internals)]: {url: 'https://login.somenewloginpage'}" My intention is to open a new page using that URL, but unfortunately it does not redirect t ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

Tips for composing a hyperlink within a property

I'm a newbie to Vue.js and facing a challenge with assigning a property to a link. I'm unsure of how to write the "counter" variable from "data" in order for it to properly function as intended. export default { name: 'app', data ( ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Unable to display content on page when using node.js and express

I have organized my controllers in the following manner... const Landmark = require('../models/landmark'); function indexRoute(req, res, next) { Landmark .find() .exec() .then((landmark) => res.render('/landmarks/index', { l ...

unable to retrieve the response from a POST request sent to a node server

Currently in the process of learning how to utilize node and express, I have embarked on creating a sample website that incorporates both along with the Google translate API. The goal is to explore the numerous features offered by these technologies. Unfor ...

The Facebook app is experiencing issues on Chrome, yet is functioning properly on Firefox

Lately, I've ventured into the world of creating Facebook Apps on heroku. After creating a test app and uploading a page with HTML5, CSS, and Javascript, I encountered an issue where the app wasn't displaying correctly in Google Chrome , but work ...

Load public and admin code dynamically using AJAX for WordPress, ensuring compatibility on all fronts

I'm facing an issue with loading front-end and admin area code in my WordPress plugin. I want the file and class responsible for creating the admin area to load only on the admin side, and the ones needed for the front-end to load exclusively on the f ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

Introducing a fresh Backbone object attribute that points to an existing instance property

While working with Backbone/Marionette, I came across something unusual. When I create a new instance of a view with a new collection property and then create another instance of the same view, it seems that the collection property of the second view point ...

Combining two JSON datasets using specific fields in Javascript

Two JSON inputs are provided: [ { userId: 32159, userFirstName: "john", userLastName: "doe", plans: [ ] }, { userId: 32157, userFirstName: "dave", userLastName: "mess", plans: [ ] } ] and [ { userId: ...