1

Using jQuery validation, I send an AJAX request which is handled by the controller. The controller does send a response, but jQuery fails to insert the respective error message into the DOM. Instead, it inserts the entire contents of the view - index.jsp - into the DOM.

I'm new to Java, and I'm completely stuck, so any help would be greatly appreciated.

My form (index.jsp)

<form class="form-inline" id="loginForm" role="form" style="margin-top: 20px">
    <div class="form-group">
        <input type="text" name="username" class="form-control" id="username" placeholder="Enter your username"
        autocomplete="off" autocapitalize="off">
    </div>
    <div class="form-group">
        <input type="password" name="password" class="form-control" id="password" placeholder="Enter your password"
        autocomplete="off" autocapitalize="off">
    </div>
    <div class="form-group">
        <button type="submit" name="loginBtn" class="btn btn-default" id="loginBtn">Log in</button>
    </div>
    <label class="formErrorMsg" id="loginErrorMsg" for="loginBtn"></label>
</form>

jQuery

$(document).ready(function(){
    // Check that the login credentials entered are valid
    $("#loginBtn").click(function(){
        event.preventDefault();
        $.post("/login", {username : $("#username").val()}, function(result){
            $("#loginErrorMsg").html(result)
        });
    });
});

Controller

@Controller
public class IndexController {

    @RequestMapping(value = "/")
    public ModelAndView returnIndexPage() {
        ModelAndView model = new ModelAndView("index");
        return model;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String checkLoginCredentials(@RequestParam("username") String username){
        return username;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.