Spring MVC Post Form Submit AJAX jQuery

Spring MVC Post Form Submit AJAX jQuery

In this tutorial you will see how to post form data submit using AJAX and jQuery in Spring MVC application. We will process response from the server and shows data on alert message.

  • Download project from below and import to eclipse as maven projec
  • Below is final project struecture

Spring MVC Post Form Submit AJAX jQuery

  • SumbitForm.jsp:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC submit form AJAX JQuery</title>
<script src="http:////code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
	
	$(document).ready(function() {

		$('#submitForm').submit(function(e) {
			var frm = $('#submitForm');
			e.preventDefault();

		    var data = {}
		    var Form = this;

		    //Gather Data also remove undefined keys(buttons)
		    $.each(this, function(i, v){
		            var input = $(v);
		        data[input.attr("name")] = input.val();
		        delete data["undefined"];
		    });
        $.ajax({
            contentType : 'application/json; charset=utf-8',
            type: frm.attr('method'),
            url: frm.attr('action'),
            dataType : 'json',
            data : JSON.stringify(data),
            success : function(callback){
            	alert("Response: Name: "+callback.name+"  DOB: "+callback.dob+"  Email: "+callback.email+"  Phone: "+callback.phone);
                $(this).html("Success!");
            },
            error : function(){
                $(this).html("Error!");
            }
        });
		});
	});
</script>
</head>
<body>
<form:form commandName="user" action="submitForm.web" method="post" id="submitForm">     

	    <fieldset style="width: 300px;">
	        <legend>User details</legend>
	        <ol>
	            <li>
	                <p><label for=name>Name</label>
	                <form:input path="name"  type="text" placeholder="First and last name" /></p>
	            </li>
	             <li>
                    <label for=name>Date</label>
                	<form:input path="dob" type="date" required="true" />
                </li>
	            <li>
	                <p><label for=email>Email</label>
	                <form:input path="email" type="text" required="true" /></p>
	            </li>
	            <li>
	                <p><label for=phone>Phone</label>
	                <form:input path="phone" type="text" required="true" /></p>
	            </li>
	         </ol>
	    </fieldset>

		<fieldset style="width: 300px;">
			<input id="submitId" type="submit" value="Submit Form">
		</fieldset>
	</form:form> 		
        
</body>
</html>
  • Users.java:
package com.javahonk.controller;

public class Users {
	private String name;
	private String dob;
	private String email;
	private String phone;

	public Users(String name, String dob, String email, String phone,
			String address, Long pincode, String country) {
		super();
		this.name = name;
		this.dob = dob;
		this.email = email;
		this.phone = phone;
	}

	public Users() {
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDob() {
		return dob;
	}

	public void setDob(String dob) {
		this.dob = dob;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
}
  • SpringMVCController.java:
package com.javahonk.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class SpringMVCController {
	
	
	@RequestMapping(value = "/helloWorld.web", method = RequestMethod.GET)
	public ModelAndView printWelcome(@ModelAttribute("user") Users user) {

		ModelAndView mav = new ModelAndView("SubmitForm");
		mav.addObject("message", "Hello World!!!");
		return mav;

	}

	@RequestMapping(value="/submitForm.web", method = RequestMethod.POST)
    public @ResponseBody Users  submittedFromData(@RequestBody Users user, HttpServletRequest request) {	
		return user;
	}	
	
}
  • For this demo we have run this project on tomcat 7.0 below is output:

Spring MVC Post Form Submit AJAX jQuerySpring MVC Post Form Submit AJAX jQuery

Spring MVC Post Form Submit AJAX jQuery

  • For more information about submit post data using jQuery and AJAX please use this link 

download  Download Project:  SpringMVCAJAXFormSubmit

11 thoughts on “Spring MVC Post Form Submit AJAX jQuery”
  1. Hello sir,
    When I run this tutorial sample, I go this error
    please help sir
    The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

  2. I got exactly the same annoying error : 415 Unsupported Media Type.
    But i have :

    org.codehaus.jackson
    jackson-mapper-asl
    1.9.10

    and spring 4.1.7 (i upgrated in case)

    and

    What is wrong?

  3. I’m very thanks for your exercise that can make me when i have problem. I hop that you upload new exercise soon. Many thank!

  4. This logic “Gathering the Data” works for text fields, but does not work for checkboxes. It always transfers the “value” of the checkbox element regardless whether the checkbox is checked or not.

    // Gather Data also remove undefined keys(buttons)
    $.each(this, function(i, v) {
    var input = $(v);

    if (input.attr(“type”) == “checkbox”)
    data[input.attr(“name”)] = input.checked ? true : false;
    else
    data[input.attr(“name”)] = input.val();

    delete data[“undefined”];
    });

  5. It actually worked for me, but I have another doubt, if you are so kind as to answer: What is the way of making the ajax call if one of the form fields is a file?

  6. I am using knouckout js , ajax with html page with Spring framework. I am not able to send data from spring controller to html page. any comment on this ?

    1. @RequestMapping(value = “/ajaxWsCustomerRegister”,method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
      @ResponseBody
      public ModelAndView makeCustomerRegisterWebService(@RequestBody String json, HttpServletResponse response) throws IOException, ParseException{
      ObjectMapper mapper = new ObjectMapper();
      RegisterModel requestValue = mapper.readValue(json, RegisterModel.class);
      String email =requestValue.getEmail();
      String password = requestValue.getPassword();
      String arsnumber = requestValue.getArsnumber();
      String ssn = requestValue.getSsn();
      JSONObject inputJsonObject = new JSONObject();
      inputJsonObject.put(“arsnumber”, arsnumber);
      String result = postDataToWebservice(inputJsonObject,”register”);
      JSONParser jsonParser = new JSONParser();
      JSONObject customerSSNFromCUBS = (JSONObject) jsonParser.parse(result);
      String ssnFromCUBS = (String) customerSSNFromCUBS.get(“ssn”);
      ModelAndView modelAndView = new ModelAndView();
      if(ssnFromCUBS.substring(2).equalsIgnoreCase(ssn))
      {
      System.out.println(“SSN matched-“+ssnFromCUBS);
      boolean isCustomerRegistered=customerDao.register(email,password,ssn,arsnumber);
      System.out.println(“Is Customer registered in db? “+isCustomerRegistered);
      if(isCustomerRegistered)
      {
      modelAndView.addObject(“result”, “customer registered sucessfully”);
      modelAndView.setViewName(“sucess”);
      }
      else
      {
      modelAndView.addObject(“message”, “customer not registered due to DB”);
      modelAndView.setViewName(“errorpage”);
      }
      }
      else
      {
      System.out.println(“SSN expected-“+ssnFromCUBS+””+ssn);
      modelAndView.addObject(“message”, “incorrect ssn”);
      modelAndView.setViewName(“errorpage”);
      }
      return modelAndView;
      }

      i am using model and view but how java object bind with it.

Leave a Reply

Your email address will not be published. Required fields are marked *