JSON data not displaying in div element using JavaScript

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?

check your network tab in dev tools - see if the jsp is actually returning valid json. could be a server issue or wrong endpoint path. also throw a console.log(users) right after the json response to see what data you’re getting back.

I’ve hit this same problem before - it’s usually JSP compilation or database connection issues. Your JavaScript looks good, but the JSP might be throwing an exception that’s getting buried. Add some debug output to your JSP first: throw in a out.println("Debug: searchParam = " + searchParam); right at the top to see if the parameter’s coming through. Also test your DBConnection.getConnection() separately to make sure it’s actually working. One more thing - you’re using result.getInt() for userId then accessing it as user.userId in JavaScript. Double-check that your database column is actually an integer. JSPs can compile fine but fail silently when they run, especially with database stuff.

I hit this exact issue last month - JSP error handling was the problem. When your database query fails, the JSP spits out HTML error content instead of JSON, so response.json() fails silently. Wrap your entire JSP logic in a proper JSON error response structure. Also check if your org.json library’s actually on the server - missing dependencies cause silent failures in JSP all the time. Another thing I found: some servers cache JSP responses like crazy, so you’ll see stale results even after fixing your code. Add a timestamp parameter to your fetch URL like endpoint + "&t=" + Date.now() to bypass caching. No console errors means the JSON parsing’s failing quietly.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.