Jquery pass Json data from HTML to Servlet in Ajax - Java @ Desk

Friday, February 3, 2017

Jquery pass Json data from HTML to Servlet in Ajax

Jquery pass Json data from HTML to Servlet in Ajax

In order to pass JSON data from HTML to servlet, javascript object is created and values are set into user defined properties of the object. Data is passed in String json format using JSON.stringify(jsonData).

Data is passed using the data attribute of ajax service.

Below example is to illustrate the same. Value of a textbox is passed to a servlet in JSON String format.

HTML File:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/common.js"></script>
<script src="js/jquery-ui.min.js"></script>

</head>
<body>
 <form id="inputform">
  <div style="height: 40px;"></div>

  <input type="text" id="textBox" name="textBox"> <input
   type="button" value="Identify" onclick="submitJsonPostData()" />
 </form>
</body>
</html>


JS File:
function submitJsonPostData() {
 var text = $("#textBox").val();
 var jsonData = new Object();
 jsonData.text = text;
 $.ajax({
  url : 'JsonPostDataServlet',
  type : 'POST',
  data : {
   jsonPostRequest : JSON.stringify(jsonData)
  },
  success : function(response) {
  },
  error : function(response) {
   alert("Error: Timeout please try again later");
  },
 });
}




Servlet:
package com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/JsonPostDataServlet")
public class JsonPostDataServlet extends HttpServlet {
 @SuppressWarnings("unchecked")
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String jsonPostRequest = request.getParameter("jsonPostRequest");
  System.out.println("Json Post Request received from JSP - " + jsonPostRequest);
 }
}


Output:
Json Post Request received from JSP -
{"text":"TextValue"}






1 comment:

  1. Wow Great!. Will you have an example to do the opposite? Receive Json data from the servlet and display it in HTML with Ajax.

    ReplyDelete