Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Send data through ajax call and receive Json response from controller in Springs

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 492
    Comment on it

    Here is the sample code implementing ajax call to send the data of a form to the controller and receiving json response from controller.

    Create a java bean class and generate setter and getter.

    public class Student
        private String name;
        private String pass;
        private String email;
        public String getName() {
            return name;
        public void setName(String name) {
   = name;
        public String getPass() {
            return pass;
        public void setPass(String pass) {
            this.pass = pass;
        public String getEmail() {
            return email;
        public void setEmail(String email) {
   = email;

    Here, we are using @ResponseBody annotation to convert the student object into its equivalent json response object. This controller handles the ajax request and return the json response.

    public class DemoController
        @RequestMapping(value="/accept" ,method= RequestMethod.POST)
        public @ResponseBody Student Registration(HttpServletRequest req,HttpServletResponse res)
            System.out.println("********inside accept");
            String nm=req.getParameter("name");
            String em=req.getParameter("email");
            String ps=req.getParameter("pass");
            Student student=new Student();
            student.setSuccess("Successfully registered");
            return student;


    Ajax implementation: here we are using serialize() method to serialize the form elements.

    $(document).ready(function() {
    $(document).on('submit', '#regForm', function(e) {
            type: "POST",
            url: 'accept',
            data: $(this).serialize(),  //it will serialize the data of the form
            success: function(response){


    This is the welcome page of the web application.

    <!DOCTYPE html>
    <script src=""></script>
    <form id="regForm"method="post" > 
    <table  align="center"> 
        <tr><td>Registration Form</td></tr> 
        <tr><td>Name</td><td><input type="text" name="name"></td></tr> 
        <tr><td>Password</td><td><input type="text" name="pass"></td></tr> 
        <tr><td>Email</td><td><input type="text" name="email"></td></tr> 
        <tr><td><input type="submit" value="register" align="middle"></td></tr> 
    <div id=final></div>

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: