I’m trying to show JSON data on my webpage but nothing appears in the target div. When I click the search button, the function runs but no results show up even though there are no errors in console.
function findUser() {
const searchTerm = document.getElementById("userInput").value.trim();
const displayArea = document.getElementById("userResults");
if (!searchTerm) {
alert("Please enter an ID or phone number.");
return;
}
displayArea.innerHTML = "<p>Loading...</p>";
const endpoint = "findUser.jsp?search=" + encodeURIComponent(searchTerm);
fetch(endpoint)
.then(response => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then(users => {
displayArea.innerHTML = "";
if (!users || users.length === 0) {
displayArea.innerHTML = "<p>No users found.</p>";
return;
}
displayArea.innerHTML = "<p>Found " + users.length + " user(s).</p>";
users.forEach(user => {
const userElement = document.createElement("div");
userElement.className = "user-item";
userElement.innerHTML = `
<p><strong>ID:</strong> ${user.userId}</p>
<p><strong>Name:</strong> ${user.userName}</p>
<p><strong>Phone:</strong> ${user.phoneNumber}</p>
<p><strong>Issue:</strong> ${user.mainIssue}</p>
`;
displayArea.appendChild(userElement);
});
})
.catch(error => {
console.error("Fetch error:", error);
displayArea.innerHTML = "<p>Could not load user data.</p>";
});
}
Here’s my JSP file that queries the database:
<%@page import="database.DBConnection"%>
<%@ page import="java.sql.*, org.json.*, java.io.*" %>
<%@ page contentType="application/json" pageEncoding="UTF-8" %>
<%
response.setCharacterEncoding("UTF-8");
String searchParam = request.getParameter("search");
JSONArray userList = new JSONArray();
if (searchParam != null && !searchParam.trim().isEmpty()) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null;
try {
connection = DBConnection.getConnection();
String query = "SELECT * FROM users WHERE userId = ? OR phoneNumber = ?";
statement = connection.prepareStatement(query);
statement.setString(1, searchParam);
statement.setString(2, searchParam);
result = statement.executeQuery();
while (result.next()) {
JSONObject user = new JSONObject();
user.put("userId", result.getInt("userId"));
user.put("userName", result.getString("userName"));
user.put("phoneNumber", result.getString("phoneNumber"));
user.put("mainIssue", result.getString("primary_concern"));
userList.put(user);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try { if (result != null) result.close(); } catch (Exception ex) {}
try { if (statement != null) statement.close(); } catch (Exception ex) {}
try { if (connection != null) connection.close(); } catch (Exception ex) {}
}
}
out.print(userList.toString());
%>
The function executes without errors but the div stays empty. What could be wrong with my code?