Quantcast
Channel: Active questions tagged servlets - Stack Overflow
Viewing all articles
Browse latest Browse all 715

Jquery Datatable not working in the JSP file

$
0
0
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Delete/Edit records</title><style>        @import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap");        body {            font-family: "Montserrat", sans-serif;            margin: 0;            padding: 20px;        }        #popupForm, #confirmationModal {            display: none;            position: fixed;            left: 50%;            top: 50%;            transform: translate(-50%, -50%);            border: 1px solid #888;            padding: 20px;            background-color: white;            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);            z-index: 1000;            width: 30%;        }        form {            padding: 30px;        }        input, select {            margin-bottom: 20px;            border: 1px solid #ddd;            border-radius: 5px;            padding: 10px;            width: 94%;            font-size: 16px;        }        label {            margin-bottom: 10px;            font-weight: 700;        }        #popupBackground, #confirmationBackground {            display: none;            position: fixed;            top: 0;            left: 0;            width: 100%;            height: 100%;            background-color: rgba(0, 0, 0, 0.5);            z-index: 500;        }        .header {            display: flex;            justify-content: space-between;            align-items: center;            padding: 20px 0;        }        .logo img {            width: 60%;        }        .header-buttons {            display: flex;            align-items: center;        }        .header-buttons a, .header-buttons button {            margin-left: 20px;            padding: 10px 20px;            border-radius: 5px;            border: 1.2px solid #0096da;            color: white;            background-color: #0096da;            cursor: pointer;            text-decoration: none;            transition: 1s ease;        }        .header-buttons button {            font-size: 16px;            font-family: "Montserrat", sans-serif;        }        .header-buttons a:hover, .header-buttons button:hover {            color: #0096da;            background: none;        }        table {            width: 100%;            border-collapse: collapse;            margin-top: 20px;        }        tbody a {            display: inline-block;            padding: 8px 16px;            margin: 4px;            border-radius: 5px;            border: 1.2px solid #0096da;            color: white;            background-color: #0096da;            text-decoration: none;            transition: 0.3s ease;        }        tbody a:hover {            color: #0096da;            background: none;            border-color: #0096da;        }        th, td {            padding: 10px;            text-align: left;            border-bottom: 1px solid #ddd;        }        th {            background-color: #ddd;            padding-bottom: 20px;            padding-top: 20px;        }        tr:hover {            background-color: #f5f5f5;        }        h1 {            margin-right: 10px;        }        .btn-container {            display: flex;            margin-top: 20px;            justify-content: center;            align-items: center;        }        .btn-container button {            width: 40%;            padding: 10px;            margin-left: 20px;            border-radius: 5px;            border: 1.2px solid #0096da;            color: white;            background-color: #0096da;            cursor: pointer;            transition: 1s ease;        }        .btn-container button:hover {            color: #0096da;            background: none;        }        #successMessage {            display: none;            position: fixed;            left: 50%;            top: 20%;            transform: translate(-50%, -50%);            border: 1px solid #888;            padding: 20px;            background-color: #dff0d8;            color: #3c763d;            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);            z-index: 1000;        }        #active-records-table {            margin-bottom: 60px;        }</style><link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css"><script src="https://code.jquery.com/jquery-3.5.1.js"></script><script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script></head><body><div class="header"><div class="logo"><img alt="" src="Images/AGCL.png"></div><h1>Edit/Delete Records</h1><div class="header-buttons"><a href="admin_dashboard.jsp">Go Back</a></div></div><h2>Active Records</h2><div id="active-records-table"><table id="activeRecordsTable"><thead><tr><th>ID</th><th>Name</th><th>Phone Number</th><th>Email</th><th>Designation</th><th>Department</th><th>Status</th><th>Actions</th></tr></thead><tbody><c:forEach var="record" items="${activeRecords}"><tr><td>${record.id}</td><td>${record.name}</td><td>${record.phoneNumber}</td><td>${record.email}</td><td>${record.post}</td><td>${record.department}</td><td>${record.status}</td><td><a href="EditRecordServlet?id=${record.id}">Edit</a><a href="javascript:confirmDelete(${record.id})">Delete</a></td></tr></c:forEach></tbody></table></div><h2>Inactive Records</h2><div id="inactive-records-table"><table id="inactiveRecordsTable"><thead><tr><th>ID</th><th>Name</th><th>Phone Number</th><th>Email</th><th>Designation</th><th>Department</th><th>Status</th><th>Actions</th></tr></thead><tbody><c:forEach var="record" items="${inactiveRecords}"><tr><td>${record.id}</td><td>${record.name}</td><td>${record.phoneNumber}</td><td>${record.email}</td><td>${record.post}</td><td>${record.department}</td><td>${record.status}</td><td><a href="EditRecordServlet?id=${record.id}">Edit</a></td></tr></c:forEach></tbody></table></div><!-- Confirmation modal --><div id="confirmationBackground" onclick="toggleConfirmationModal()"></div><div id="confirmationModal"><h2>Confirm Deletion</h2><p>Are you sure you want to delete this record?</p><div class="btn-container"><button id="confirmDeleteButton">Yes</button><button onclick="toggleConfirmationModal()">No</button></div></div><!-- Hidden iframe for form submission --><iframe id="hiddenIframe" name="hiddenIframe" style="display:none;" onload="iframeLoadHandler()"></iframe><!-- Success message --><div id="successMessage">Record updated successfully!</div><script type="text/javascript">    $('#activeRecordsTable').DataTable();    $('#inactiveRecordsTable').DataTable();        function togglePopupForm() {            var form = document.getElementById("popupForm");            var background = document.getElementById("popupBackground");            if (form.style.display === "none") {                form.style.display = "block";                background.style.display = "block";            } else {                form.style.display = "none";                background.style.display = "none";            }        }        function toggleConfirmationModal() {            var modal = document.getElementById("confirmationModal");            var background = document.getElementById("confirmationBackground");            if (modal.style.display === "none") {                modal.style.display = "block";                background.style.display = "block";            } else {                modal.style.display = "none";                background.style.display = "none";            }        }        function confirmDelete(recordId) {            toggleConfirmationModal();            document.getElementById('confirmDeleteButton').onclick = function() {                window.location.href = 'DeleteRecordServlet?id='+ recordId;            }        }        function iframeLoadHandler() {            var iframe = document.getElementById('hiddenIframe');            var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;            var responseText = iframeDocument.body.textContent || iframeDocument.body.innerText;            if (responseText.trim() === 'success') {                togglePopupForm();                showSuccessMessage('Record added successfully!');                fetchRecords();            } else if (responseText.trim() === 'error') {                alert('An error occurred while adding the record.');            }        }        function fetchRecords() {            fetch('deleteDashboard')                .then(response => response.text())                .then(data => {                    const tempElement = document.createElement('div');                    tempElement.innerHTML = data;                    // Update the active records table                    const newActiveTableBody = tempElement.querySelector('#active-records-table tbody');                    if (newActiveTableBody) {                        document.querySelector('#active-records-table tbody').innerHTML = newActiveTableBody.innerHTML;                    }                    // Update the inactive records table                    const newInactiveTableBody = tempElement.querySelector('#inactive-records-table tbody');                    if (newInactiveTableBody) {                        document.querySelector('#inactive-records-table tbody').innerHTML = newInactiveTableBody.innerHTML;                    }                });        }        function showSuccessMessage(message) {            var successMessage = document.getElementById("successMessage");            successMessage.innerText = message;            successMessage.style.display = "block";            setTimeout(function() {                successMessage.style.display = "none";            }, 3000);        }        window.onload = function() {            fetchRecords();            const urlParams = new URLSearchParams(window.location.search);            if (urlParams.has('updateSuccess')) {                showSuccessMessage('Record updated successfully!');            }            if (urlParams.has('deleteSuccess')) {                showSuccessMessage('Record deleted successfully!');            }        }</script></body></html>

SO here I have implemented the Datable its showing the button but they are not working [enter image description here](https://i.sstatic.net/Wx7S55Gw.png)

After running the server, when I search It just shows no recordsBelow is the servlet

package servlets;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import java.util.Properties;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/deleteDashboard")public class deleteDashboard extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        HttpSession session = request.getSession(false);        if (session == null || session.getAttribute("adminId") == null) {            response.sendRedirect("admin_login.jsp");            return;        }        Properties props = new Properties();        try (InputStream input = getServletContext().getResourceAsStream("/WEB-INF/config.properties")) {            if (input == null) {                request.setAttribute("errorMessage", "Sorry, unable to find config.properties");                request.getRequestDispatcher("error.jsp").forward(request, response);                return;            }            props.load(input);        } catch (IOException ex) {            ex.printStackTrace();        }        String dbUrl = props.getProperty("db.url");        String dbUser = props.getProperty("db.user");        String dbPassword = props.getProperty("db.password");        String dbQueryActive = props.getProperty("db.query.active");        String dbQueryInactive = props.getProperty("db.query.inactive");        try {            Class.forName("org.postgresql.Driver");            Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPassword);            // Fetch active records            PreparedStatement psActive = con.prepareStatement(dbQueryActive);            ResultSet rsActive = psActive.executeQuery();            List<Record> activeRecords = new ArrayList<>();            while (rsActive.next()) {                Record record = new Record();                record.setId(rsActive.getInt("id"));                record.setName(rsActive.getString("name"));                record.setPhoneNumber(rsActive.getString("phone_number"));                record.setEmail(rsActive.getString("email"));                record.setStatus(rsActive.getString("status"));                record.setPost(rsActive.getString("post"));                record.setDepartment(rsActive.getString("department"));                activeRecords.add(record);            }            request.setAttribute("activeRecords", activeRecords);            // Fetch inactive records            PreparedStatement psInactive = con.prepareStatement(dbQueryInactive);            ResultSet rsInactive = psInactive.executeQuery();            List<Record> inactiveRecords = new ArrayList<>();            while (rsInactive.next()) {                Record record = new Record();                record.setId(rsInactive.getInt("id"));                record.setName(rsInactive.getString("name"));                record.setPhoneNumber(rsInactive.getString("phone_number"));                record.setEmail(rsInactive.getString("email"));                record.setStatus(rsInactive.getString("status"));                record.setPost(rsInactive.getString("post"));                record.setDepartment(rsInactive.getString("department"));                inactiveRecords.add(record);            }            request.setAttribute("inactiveRecords", inactiveRecords);            con.close();        } catch (Exception e) {            e.printStackTrace();        }        request.getRequestDispatcher("delete.jsp").forward(request, response);    }}

So here in this code I am fetching the records that are active and inactive. after that I have enabled jquery datatable in it buts its not working its showing the search, etc but when I am using then its showing error. I have tried console logging the error, its showing that both jquery and datatable are loading properly. Actually its was working properly at first then when I edit the data it stopped working


Viewing all articles
Browse latest Browse all 715

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>