Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Handling JSON Data in AJAX Responses

Tech 3

When a server returns simple data, plain text is sufficient and easy to handle. Both frontend and backend implementations remain straightforward.

Frontend HTML/JavaScript:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AJAX Response Formats</title>
    <script>
        let httpRequest;
        function fetchData() {
            httpRequest = new XMLHttpRequest();
            httpRequest.open('GET', 'textDataHandler', true);
            httpRequest.onreadystatechange = displayData;
            httpRequest.send();
        }
        function displayData() {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                let responseText = httpRequest.responseText;
                console.log(responseText);
            }
        }
    </script>
</head>
<body>
    <button type="button" onclick="fetchData()">Get Data</button>
</body>
</html>

Backend Servlet (Java):

@WebServlet("/textDataHandler")
public class TextDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print("Simple text response");
    }
}

Processing complex data like objects or collections as plain text becomes cumbersome. JSON (JavaScript Object Notation) is a lightweight data interchange format ideal for this purpose. It is language-independent, human-readable, and easily parsed by machines, making network transmission efficient.

Key Advantages:

  1. Lightweight, designed for data serialization.
  2. Copmatible with both frontend JavaScript objects and backend data structures.
  3. Can be directly parsed into JavaScript objects.
  4. The default data format for many AJAX libraries, including jQuery.

JSON Syntax and Usage in JavaScript:

// Creating a JSON object
let employee = {"firstName": "John", "employeeId": 101};
alert(employee.firstName); // John
alert(employee.employeeId); // 101

// Creating an array of JSON objects
let team = [
    {"firstName": "Alice", "employeeId": 102},
    {"firstName": "Bob", "employeeId": 103},
    {"firstName": "Charlie", "employeeId": 104}
];

for (let member of team) {
    console.log(member.firstName);
    console.log(member.employeeId);
}

// Converting a JSON string to a JavaScript object
let jsonString = '{"firstName": "David", "employeeId": 105}';
let parsedObj = JSON.parse(jsonString);
console.log(parsedObj.firstName); // David
console.log(parsedObj.employeeId); // 105

Relationship between JSON and JavaScript Objects: JSON is a string representation of a JavaScript object.

// A JavaScript object
let jsObject = {id: 1, status: "active"};
// A JSON string (note the quotes around property names)
let jsonStringRep = '{"id": 1, "status": "active"}';

Conversion Methods:

  • JSON string to JS Object: JSON.parse()
    let obj = JSON.parse('{"key": "value"}');
    
  • JS Object to JSON string: JSON.stringify()
    let jsonStr = JSON.stringify({key: "value"});
    

Manually constructing JSON strings is error-prone, especially with many fields. Using a library like Gson (for Java) automates conversion between Java objects and JSON.

Using Gson for Backend Serialization:

Frontend (Receiving and Parsing JSON):

<script>
    let ajaxReq;
    function requestUserData() {
        ajaxReq = new XMLHttpRequest();
        ajaxReq.open('GET', 'userDataServlet', true);
        ajaxReq.onreadystatechange = processResponse;
        ajaxReq.send();
    }
    function processResponse() {
        if (ajaxReq.readyState === 4 && ajaxReq.status === 200) {
            let responseJson = ajaxReq.responseText;
            let userList = JSON.parse(responseJson);
            for (let usr of userList) {
                console.log(usr.username);
                console.log(usr.yearsOld);
                console.log(usr.sex);
                console.log(usr.joinDate);
            }
        }
    }
</script>
<input type="button" value="Load Users" onclick="requestUserData()">

Backend Servlet with Gson:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

// Assume a User class exists with fields: username, yearsOld, sex, joinDate
@WebServlet("/userDataServlet")
public class UserDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // Create sample data
        List<User> users = Arrays.asList(
            new User("Alex", 25, "M", new Date()),
            new User("Jamie", 30, "F", new Date()),
            new User("Casey", 28, "M", new Date())
        );

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        // Configure Gson for date formatting and convert list to JSON
        Gson gsonConverter = new GsonBuilder()
                                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                                .create();
        String jsonOutput = gsonConverter.toJson(users);

        // Send JSON response
        resp.getWriter().print(jsonOutput);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.