Thursday 25 September 2014

Send HTML Form Data as JSON via Ajax

Hi Guys,


There's a lot of confusion among new developers on which format they want to send the data to server. Some use JQuery API's and some use normal form data. In this post we will see how to send form data as JSON to server.
First question that would surely come to your mind is why to send JSON to server? Is there any advantage of sending data as JSON? it depends upon what your web app does and what data you are sending? If structure of data is really complex then JSON must be used in order to reduce parsing complexity.  Sometimes you have web application that accepts/prefers JSON data coming from client end so in such cases you need to convert your form’s data in JSON and post it to server.
So for sending data as JSON we need to use $('#formname').serializeObject() method in JQuery and process form ouput to JSON format. Lets see how to achieve this.

Step 1:
Create a Dynamic Web application project in Java. Create index.jsp under Web-content folder.Include jquery.serializeObject.js plugin. Refer https://github.com/hongymagic/jQuery.serializeObject for more details on plugin.
Once we serialize our Form data to JSON we need to use JSON.stringify() method for converting Object to JSON text and stores that in a string.
Once we get the JSON text as String we can able to send that data to our Servlet using Ajax Request.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="js/jquery.serializeObject.js"></script>
<script>
$(document).ready(function(){
$("#simplepost").click(function(e)
{
var data = $('#ajaxform').serializeObject();
 $.ajax({
    type: 'POST',
    url: 'Json',
    dataType : 'json',
    data: JSON.stringify(data),
    success: function (response) {
    console.log(response);   
    },
    error:function(request, textStatus, errorThrown) {
        alert(errorThrown);
    }
}); 

});
});
</script>
</head>
<body>

<div id="message">
<form id="ajaxform" method="POST">
First Name: <input type="text" name="fname"> <br/>
Last Name: <input type="text" name="lname"> <br/>
Email : <input type="text" name="email"> <br/>
<input type="button" class="btn btn-info" id="simplepost" value="Run Code"></form>
 </div>
</body>
</html>
Step 2:
Create a Java bean called Data under src/package. In Java i am using Java Jackson Processor for mapping my JSON data with Java bean. You can refer http://jackson.codehaus.org/ for more details on Jackson processing.
@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {

private String fname;
private String email;
private String lname;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;

}
}
Step 3:
Create another Java bean called Response for processing the response.
public class Response {

private String response;

public String getResponse() {
return response;
}

public void setResponse(String response) {
this.response = response;
}

}
Step 4:
Create Java Servlet called Json for processing our data which we send through Ajax Request from our client.
public class Json extends HttpServlet {
private static final long serialVersionUID = 1L;
       
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));

  String json = "";
        if(br != null){
            json = br.readLine();
        }
        
        ObjectMapper mapper = new ObjectMapper();
        Data data = mapper.readValue(json, Data.class);
        String fname = "Fname:"+data.getFname()+" ";
        String lname = "LNAme: "+data.getLname()+" ";
        String email = "E-Mail: "+data.getEmail()+" ";
        
        try
        {
        File file =new File("C:/Users/padmakvis/Desktop/data.txt");
        if(!file.exists()){
        System.out.println("Creating file...");
        file.createNewFile();
}
        System.out.println("Reading Data");
        FileWriter fileWriter = new FileWriter(file,true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWriter);
        fileWriter.append(fname);
        fileWriter.append(lname);
        fileWriter.append(email);
        bufferWritter.newLine();
        bufferWritter.close();
        System.out.println("File write Successfully...");
        }catch(IOException e)
        {
        e.printStackTrace();
        }
        
        Response responseData = new Response();
        responseData.setResponse("Data Stored Successfully");
        response.setContentType("application/json");          
        mapper.writeValue(response.getOutputStream(), responseData);
        
}catch(Exception e)
{e.printStackTrace();}
}


}
I am using Object Mapper class for mapping my JSON data with Java bean. Once we map the data we can get all the fields what ever we are sending through Ajax request. After getting all the data i am writing the data to a text file using file-writer. Once the request got processed successfully we need to send response back to our client via Ajax. For that i am using mapper.writeValue() method from Jackson processor.

That's all Folk's