John S.
John S.

Reputation: 13

Slow loading data into two grids at launch or after a refresh

My goal is to create a web page with a combo box populated with various dates. The first date would be the date selected by default. Based on the selected date, two tabs each with a distinct grid would display their own data.

Since I am new in terms of programming with 'jQuery,' I have enlisted the help of AI in order to create my web page. After a fairly lengthy back and forth with AI, I do have a locally working web page. However, the loading of the page is extremely slow. After the initial load, the navigation within the page is very fast.

Here is my 'js' code:

$(document).ready(function () {
    // Initialize count variables
    let silentAuctionCount = 0;
    let liveAuctionCount = 0;
    // Function to update the record count
    function updateRecordCount(tableId, footerId, count) {
        $(footerId).text('Item count: ' + count);
    }
    // Function to show only the active tab's footer
    function updateFooterVisibility() {
        const activeTab = $('.tab.active').data('target');
        if (activeTab === 'silent-tab') {
            $('#silent-auction-footer').show();
            $('#live-auction-footer').hide();
        } else if (activeTab === 'live-tab') {
            $('#silent-auction-footer').hide();
            $('#live-auction-footer').show();
        }
    }
    // Load data when the page is loaded
    function loadData(auctionDateID = '') {
        $.get('my_test_data.php', { auctiondateid: auctionDateID }, function (data) {
            const parsedData = JSON.parse(data);
            // Populate the AuctionDateID combo box
            $('#filter-auctiondateid').empty();
            $('#filter-auctiondateid').append('<option value="">Select Auction Date</option>');
            parsedData.auction_dates.forEach(function (auctionDate) {
                $('#filter-auctiondateid').append(
                    `<option value="${auctionDate.AuctionDateID}">${auctionDate.AuctionDate}</option>`
                );
            });
            // Automatically select the first Auction Date ID (if available)
            if (parsedData.auction_dates.length > 0) {
                $('#filter-auctiondateid').val(parsedData.auction_dates[0].AuctionDateID);
            }
            // Fill the Silent Auction grid
            $('#silent-grid tbody').empty();
            parsedData.silent_auction_items.forEach(function (all_items) {
                const itemNameLink = `<a href="${all_items['Link']}" target="_blank">${all_items.ItemName}</a>`;
                $('#silent-grid tbody').append(
                    `<tr data-id="${all_items.ItemName}">
                        <td>${itemNameLink}</td>
                        <td>${all_items.ItemType}</td>
                        <td>${all_items.ItemColor}</td>
                        <td>${all_items.ItemYear}</td>
                        <td>${all_items.ItemHybridizer}</td>
                    </tr>`
                );
            });
            // Fill the Live Auction grid
            $('#live-grid tbody').empty();
            parsedData.live_auction_items.forEach(function (all_items) {
                const itemNameLink = `<a href="${all_items['Link']}" target="_blank">${all_items.ItemName}</a>`;
                $('#live-grid tbody').append(
                    `<tr data-id="${all_items.ItemName}">
                        <td>${itemNameLink}</td>
                        <td>${all_items.ItemType}</td>
                        <td>${all_items.ItemColor}</td>
                        <td>${all_items.ItemYear}</td>
                        <td>${all_items.ItemHybridizer}</td>
                    </tr>`
                );
            });
            // Update initial record counts
            silentAuctionCount = parsedData.silent_auction_items.length;
            liveAuctionCount = parsedData.live_auction_items.length;
            updateRecordCount('#silent-grid', '#silent-auction-footer', silentAuctionCount);
            updateRecordCount('#live-grid', '#live-auction-footer', liveAuctionCount);
            // Trigger click on the active tab to ensure data is displayed
            $('.tab.active').click();
        });
    }
    // Handle filtering for Auction Date ID
    $('#filter-auctiondateid').on('change', function () {
        const selectedauctiondateID = $(this).val();
        // Send an AJAX request to fetch the filtered Live Auction items
        $.get('my_test_data.php', { auctiondateid: selectedauctiondateID }, function (data) {
            const parsedData = JSON.parse(data);
            // Clear the current Silent Auction items grid
            $('#silent-grid tbody').empty();
            // Populate the Silent Auction items grid with the filtered results
            parsedData.silent_auction_items.forEach(function (all_items) {
                const itemNameLink = `<a href="${all_items['Link']}" target="_blank">${all_items.ItemName}</a>`;
                $('#silent-grid tbody').append(
                    `<tr data-id="${all_items.ItemName}">
                        <td>${itemNameLink}</td>
                        <td>${all_items.ItemType}</td>
                        <td>${all_items.ItemColor}</td>
                        <td>${all_items.ItemYear}</td>
                        <td>${all_items.ItemHybridizer}</td>
                    </tr>`
                );
            });
            // Update the Silent Auction items count
            updateRecordCount('#silent-grid', '#silent-auction-footer', parsedData.silent_auction_items.length);
            // Clear the current Live Auction items grid
            $('#live-grid tbody').empty();
            // Populate the Live Auction items grid with the filtered results
            parsedData.live_auction_items.forEach(function (all_items) {
                const itemNameLink = `<a href="${all_items['Link']}" target="_blank">${all_items.ItemName}</a>`;
                $('#live-grid tbody').append(
                    `<tr data-id="${all_items.ItemName}">
                        <td>${itemNameLink}</td>
                        <td>${all_items.ItemType}</td>
                        <td>${all_items.ItemColor}</td>
                        <td>${all_items.ItemYear}</td>
                        <td>${all_items.ItemHybridizer}</td>
                    </tr>`
                );
            });
            // Update the Live Auction items count
            updateRecordCount('#live-grid', '#live-auction-footer', parsedData.live_auction_items.length);
        });
    });
    // Handle tab switching
    $('.tab').on('click', function () {
        // Set active tab
        $('.tab').removeClass('active');
        $(this).addClass('active');
        const targetTab = $(this).data('target');
        $('.tab-content').removeClass('active');
        $('#' + targetTab).addClass('active');
        // Update footer visibility
        updateFooterVisibility();
        // Trigger product filter for Silent Auction tab
        if (targetTab === 'silent-tab') {
            $('#filter-auctiondateid').trigger('change'); // Trigger product filter on tab switch
        } else {
            // Trigger product filter for Live Auction tab
            if (targetTab === 'live-tab') {
                $('#filter-auctiondateid').trigger('change'); // Trigger product filter on tab switch
            }
        }
    });
    // Default to the first tab (Silent Auction)
    if ($('.tab.active').length === 0) {
        $('.tab:first').click();
    }
    // Load initial data with the selected Auction Date ID
    const initialAuctionDateID = $('#filter-auctiondateid').val();
    loadData(initialAuctionDateID);
    // Initially trigger product filter to show Live Auction grid with the default Auction Date ID
    $('#filter-auctiondateid').trigger('change');
    // Handle filtering
    function applyFilter(tableId, filters, footerId, count) {
        let visibleCount = 0;
        $(tableId + ' tbody tr').each(function() {
            let showRow = true;
            $(this).find('td').each(function(index) {
                const filterValue = filters[index];
                const cellText = $(this).text().toLowerCase();
                if (filterValue && !cellText.includes(filterValue.toLowerCase())) {
                    showRow = false;
                }
            });
            if (showRow) {
                $(this).show();
                visibleCount++;
            } else {
                $(this).hide();
            }
        });
        // Update the footer with the count of visible records
        $(footerId).text('Item count: ' + visibleCount);
    }
    // Filter events for the Silent Auction grid
    $('#filter-itemname, #filter-itemtype, #filter-itemcolor, #filter-itemyear, #filter-itemhybridizer').on('input', function() {
        const filters = [
            $('#filter-itemname').val(),
            $('#filter-itemtype').val(),
            $('#filter-itemcolor').val(),
            $('#filter-itemyear').val(),
            $('#filter-itemhybridizer').val()
        ];
        applyFilter('#silent-grid', filters, '#silent-auction-footer', silentAuctionCount);
    });
    // Filter events for the Live Auction grid
    $('#filter-itemname, #filter-itemtype, #filter-itemcolor, #filter-itemyear, #filter-itemhybridizer').on('input', function() {
        const filters = [
            $('#filter-itemname').val(),
            $('#filter-itemtype').val(),
            $('#filter-itemcolor').val(),
            $('#filter-itemyear').val(),
            $('#filter-itemhybridizer').val()
        ];
        applyFilter('#live-grid', filters, '#live-auction-footer', liveAuctionCount);
    });
    // Handle sorting
    let sortDirections = {
        'ItemName': 'asc',
        'ItemType': 'asc',
        'ItemColor': 'asc',
        'ItemYear': 'asc',
        'ItemHybridizer': 'asc'
    };
    function sortTable(tableId, columnIndex, direction) {
        const rows = $(`${tableId} tbody tr`).get();
        rows.sort(function(rowA, rowB) {
            const cellA = $(rowA).find(`td:eq(${columnIndex})`).text();
            const cellB = $(rowB).find(`td:eq(${columnIndex})`).text();
            return (direction === 'asc' ? cellA > cellB : cellA < cellB) ? 1 : -1;
        });
        $.each(rows, function(index, row) {
            $(tableId).children('tbody').append(row);
        });
    }
    // Sort grid columns when clicked
    $('th.sortable').on('click', function() {
        const column = $(this).data('column');
        const columnIndex = $(this).index();
        const direction = sortDirections[column] === 'asc' ? 'desc' : 'asc';
        sortDirections[column] = direction;
        sortTable(`#${$(this).closest('table').attr('id')}`, columnIndex, direction);
    });
    // Default to the first tab (Silent Auction)
    $('.tab:first').click();
});

With the help of the console, I have noticed that my 'loadData' function initially retrieves all the data before filtering it by date. The portion of the code that handles the filtering by date ('// Handle filtering for Auction Date ID') is called four times.

I must not be asking AI the right questions because I am unable to get it to help me achieve a much more efficient load time.

Any inputs/suggestions from seasoned 'jQuery' programmers would be greatly appreciated.

Thanks

Upvotes: 0

Views: 3

Answers (0)

Related Questions