XML-Based Data Exchange with AJAX
XML-Based Data Exchange
- Important: When the server responds with XML data, the content type must be set to:
response.setContentType("text/xml;charset=UTF-8");
-
Both XML and JSON are common data ecxhange formats
-
XML has larger file size and complex parsing. Less commonly used.
-
JSON has smaler size and simpler parsing. More frequently used.
-
Frontend implementation for XML-based data exchange:
<html>
<head>
<meta charset="UTF-8">
<title>Data Exchange Using XML</title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
const triggerButton = document.getElementById("fetchBtn");
triggerButton.addEventListener('click', function() {
// Initiate Ajax request
// Step 1: Create XMLHttpRequest instance
const httpReq = new XMLHttpRequest();
// Step 2: Open communication channel
httpReq.open("GET", "/data/xml-endpoint?timestamp=" + Date.now(), true);
// Step 3: Send the request
httpReq.send();
// Step 4: Monitor response
httpReq.onreadystatechange = function() {
if (httpReq.readyState === 4) {
if (httpReq.status === 200) {
// Retrieve XML response from server
// XML parser automatically converts string to document object
const xmlDocument = this.responseXML;
const studentElements = xmlDocument.getElementsByTagName("student");
let tableContent = "";
for (let index = 0; index < studentElements.length; index++) {
tableContent += "<tr>";
const currentStudent = studentElements[index];
const elementChildren = currentStudent.childNodes;
for (let childIndex = 0; childIndex < elementChildren.length; childIndex++) {
const currentNode = elementChildren[childIndex];
tableContent += "<td>" + currentNode.textContent + "</td>";
}
tableContent += "</tr>";
}
document.getElementById("studentTableBody").innerHTML = tableContent;
} else {
alert(httpReq.status);
}
}
}
});
});
</script>
<button id="fetchBtn">
Load Student Records
</button>
<table width="600px" border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Location</th>
</tr>
</thead>
<tbody id="studentTableBody" align="center">
</tbody>
</table>
</body>
</html>
- Backend Java implementation for XML-based data exchange:
package com.example.data.web;
import com.example.data.models.Student;
import com.example.data.utilities.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/xml-data-endpoint")
public class XmlDataEndpoint extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml;charset=utf-8");
PrintWriter writer = response.getWriter();
Connection dbConnection = null;
PreparedStatement statement = null;
ResultSet queryResult = null;
try {
dbConnection = DatabaseConnection.getConnection();
String query = "SELECT * FROM student_table";
statement = dbConnection.prepareStatement(query);
queryResult = statement.executeQuery();
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<students>");
while (queryResult.next()) {
int recordId = queryResult.getInt("id");
String name = queryResult.getString("name");
int studentAge = queryResult.getInt("age");
String location = queryResult.getString("location");
xmlBuilder.append("<student>");
xmlBuilder.append("<id>" + recordId + "</id>");
xmlBuilder.append("<name>" + name + "</name>");
xmlBuilder.append("<age>" + studentAge + "</age>");
xmlBuilder.append("<location>" + location + "</location>");
xmlBuilder.append("</student>");
}
xmlBuilder.append("</students>");
writer.print(xmlBuilder.toString());
} catch (Exception exception) {
exception.printStackTrace();
} finally {
DatabaseConnection.close(dbConnection, statement, queryResult);
}
}
}