Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

document.addEventListener('DOMContentLoaded', function() { // Variables to hold interval…

  1. User

    document.addEventListener('DOMContentLoaded', function() { // Variables to hold interval IDs let intervalFun; let intervalFun2;

    // Function Definitions
    
    function runInterval() {
    intervalFun = setInterval(qrcodeRequest, 5000);
    

    }

    function stopInterval() { clearInterval(intervalFun); }

    function runInterval2() {
        qrcodeRequest2();
        intervalFun2 = setInterval(qrcodeRequest2, 5000);
    }
    
    function stopInterval2() {
        clearInterval(intervalFun2);
        document.getElementById("qrcode2").classList.remove("d-block");
        document.getElementById("qrcode2").classList.add("d-none");
        document.getElementById("spinner2").classList.remove("d-none");
    }
    
    // Define addPhoneRequest function
    function addPhoneRequest() {
        var whatsapp_phone = $('#whatsapp_phone').val();  // Get the phone value from input
        var tokenAuth = $("#myToken").val();  // Get the token value
    
        console.log("request sent");  // <-- Added this line
    
        $.ajax({
            url: "{{ route('whatsapp.phone') }}",
            method: "post",
            data: {
                phone: whatsapp_phone,  // Pass the phone number correctly
                token: tokenAuth  // Add the token to the request data
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(data) {
                if (data.success == true) {
                    $("#whatsapp_phone_error").addClass("d-none");
                    document.getElementById("spinner").classList.remove("d-none");
                    document.getElementById("whatsapp_phone_form").classList.add("d-none");
                    $("#qrcode_phone").val(data.phone);
                    runInterval();
                } else {
                    $("#whatsapp_phone_error").removeClass("d-none");
                    $("#whatsapp_phone_error").html(data.message);
                }
            }
        });
    }
    
    // Define qrcodeRequest function
    function qrcodeRequest() {
        var phone = $("#qrcode_phone").val();
        var myToken = $("#myToken").val();
    
        console.log("request sent");  // <-- Added this line
    
        $.ajax({
            method: "get",
            url: "{{ route('whatsapp.qrcode') }}",
            data: {
                phone: phone,
                token: myToken
            },
            success: function(data) {
                if (data.status == 'success') {
                    if (data.qrcode.startsWith('data')) {
                        document.getElementById("qrcode").classList.remove("d-none");
                        document.getElementById("qrcode").classList.add("d-block");
                        document.getElementById("spinner").classList.add("d-none");
                        document.getElementById("qrcode").src = data.qrcode;
                    }
                }
                if (data.status == 'connected') {
                    console.log("request sent");  // <-- Added this line
                    $.ajax({
                        method: "put",
                        url: "{{ route('whatsapp.session.status') }}",
                        data: {
                            status: "connected",
                            phone: phone,
                            token: myToken  
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(data) {
                            location.reload();
                        }
                    });
                }
            }
        });
    }
    
    // Define qrcodeRequest2 function
    function qrcodeRequest2() {
        var defCheckbox = document.getElementById('defCheckbox').checked;
        var selectedCheckbox = document.querySelector('.row-checkbox:checked');
    
        if (!selectedCheckbox) {
            document.getElementById("error_phone").classList.remove("d-none");
            clearInterval(intervalFun2);
            return;
        }
    
        document.getElementById("error_phone").classList.add("d-none");
        var row = selectedCheckbox.closest('tr');
        var phone = row.cells[2].textContent.trim();
        var myToken = $("#myToken").val();
    
        console.log("request sent");  // <-- Added this line
    
        $.ajax({
            method: "get",
            url: "{{ route('whatsapp.qrcode') }}",
            data: {
                phone: phone,
                default_phone: defCheckbox,
                token: myToken
            },
            success: function(data) {
                if (data.status == 'success') {
                    if (data.qrcode.startsWith('data')) {
                        document.getElementById("qrcode2").classList.remove("d-none");
                        document.getElementById("qrcode2").classList.add("d-block");
                        document.getElementById("spinner2").classList.add("d-none");
                        document.getElementById("qrcode2").src = data.qrcode;
                    }
                }
                if (data.status == 'connected') {
                    console.log("request sent");  // <-- Added this line
                    $.ajax({
                        method: "put",
                        url: "{{ route('whatsapp.session.status') }}",
                        data: {
                            status: "connected",
                            phone: phone,
                            token: myToken  
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(data) {
                            location.reload();
                        }
                    });
                }
            }
        });
    }
    
    // Event Listeners
    
    document.getElementById('addPhoneButton').addEventListener('click', function() {
        addPhoneRequest();
    });
    
    document.getElementById('runInterval2Button').addEventListener('click', function() {
        runInterval2();
    });
    
    document.getElementById('stopIntervalButton').addEventListener('click', function() {
        stopInterval();
    });
    
    document.getElementById('stopInterval2Button').addEventListener('click', function() {
        stopInterval2();
    });
            const selectedPhones = new Set();
            const deleteBtn = document.getElementById('delbtn');
            const selectAllCheckbox = document.getElementById('selectAllCheckbox');
            const checkboxes = document.querySelectorAll('.row-checkbox');
            const deleteConfirmationModal = document.getElementById('deleteConfirmationModal');
            const closeDeleteModalElements = deleteConfirmationModal.querySelectorAll('.close, #cancelDelete');
            const confirmDeleteButton = document.getElementById('confirmDelete');
    
            /**
             * دالة لإظهار المودال
             * @param {HTMLElement} modal - عنصر المودال المراد إظهاره
             */
            function showModal(modal) {
                modal.style.display = 'block';
                document.body.classList.add('modal-open');
            }
    
            /**
             * دالة لإخفاء المودال
             * @param {HTMLElement} modal - عنصر المودال المراد إخفاءه
             */
            function hideModal(modal) {
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
            }
    
         
            function setupDeleteModal() {
                closeDeleteModalElements.forEach(element => {
                    element.addEventListener('click', () => hideModal(deleteConfirmationModal));
                });
    
                confirmDeleteButton.addEventListener('click', () => {
                    hideModal(deleteConfirmationModal);
                    deleteSelectedRows();
                });
    
                deleteBtn.addEventListener('click', function(event) {
                    event.preventDefault(); // منع السلوك الافتراضي للنقر
                    if (selectedPhones.size === 0) {
                        alert('يرجى تحديد جلسات للحذف.');
                        return;
                    }
                    showModal(deleteConfirmationModal);
                });
            }
    
        
            function deleteSelectedRows() {
                const phonesArray = Array.from(selectedPhones);
    
                fetch('/delete-sessions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({phones: phonesArray})
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        phonesArray.forEach(phone => {
                            const rows = document.querySelectorAll('tr');
                            for (let row of rows) {
                                if (row.cells[2] && row.cells[2].textContent.trim() === phone) {
                                    row.remove();
                                    break;
                                }
                            }
                        });
                        selectedPhones.clear();
                        deleteBtn.disabled = true;
                        checkboxes.forEach(checkbox => {
                            checkbox.checked = false;
                        });
                        alert('تم حذف الجلسات المحددة بنجاح.');
                    } else {
                        window.location.reload();
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    window.location.reload();
                });
            }
    
         
            function setupCheckboxes() {
                selectAllCheckbox.addEventListener('change', function() {
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                        const row = checkbox.closest('tr');
                        const phone = row.cells[2].textContent.trim();
                        if (checkbox.checked) {
                            selectedPhones.add(phone);
                        } else {
                            selectedPhones.delete(phone);
                        }
                    });
                    deleteBtn.disabled = selectedPhones.size === 0;
                });
    
                checkboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', function() {
                        const row = this.closest('tr');
                        const phone = row.cells[2].textContent.trim();
                        if (this.checked) {
                            selectedPhones.add(phone);
                        } else {
                            selectedPhones.delete(phone);
                        }
                        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
                        selectAllCheckbox.checked = allChecked;
                        deleteBtn.disabled = selectedPhones.size === 0;
                    });
                });
            }
    
            setupCheckboxes();
            setupDeleteModal();
        });
    
        $(document).ready(function() {
          $("#table").DataTable({
            pagingType: "full_numbers",
            scrollX: true,
            autoWidth: false,
          });
        }); request is not getting send and elemebt Uncaught TypeError: document.getElementById(...) is null
    <anonymous> http://127.0.0.1:8000/sessionss:660
    EventListener.handleEvent* http://127.0.0.1:8000/sessionss:497
    

    sessionss:660:14 http://127.0.0.1:8000/sessionss:660 (Async: EventListener.handleEvent) http://127.0.0.1:8000/sessionss:497

  2. Assistant

    The error message you're encountering:

    Uncaught TypeError: document.getElementById(...) is null
    

    indicates that your JavaScript code is attempting to access a DOM element with a specific ID, but it cannot find that element in the current HTML document. This is causing subsequent JavaScript execution to halt, preventing AJAX requests from being sent as expected.

    Possible Causes:

    1. Incorrect Element ID:

      • There's a typo or mismatch between the ID used in your JavaScript and the actual ID in your HTML.
    2. Element Not Present in the DOM:

      • The element with the specified ID doesn't exist in the HTML.
      • The element is dynamically generated and hasn't been added to the DOM at the time the script runs.
    3. Script Execution Order:

      • Although you've wrapped your code inside DOMContentLoaded, there might still be dependencies or asynchronous operations affecting element availability.

    Steps to Diagnose and Fix the Issue:

    1. Identify the Problematic getElementById:

      • The error message points to a specific line in your sessionss script (e.g., sessionss:660:14). Open your browser's developer tools, navigate to that line, and identify which getElementById call is failing.
    2. Verify Element IDs in HTML:

      • Ensure that every ID referenced in your JavaScript exists in your HTML. Here's a list based on your script:

        • addPhoneButton
        • runInterval2Button
        • stopIntervalButton
        • stopInterval2Button
        • qrcode2
        • spinner2
        • whatsapp_phone
        • myToken
        • whatsapp_phone_error
        • spinner
        • whatsapp_phone_form
        • qrcode_phone
        • qrcode
        • selectAllCheckbox
        • delbtn
        • deleteConfirmationModal
        • confirmDelete
        • (and any others used within the script)
      • Action: Open your HTML file and confirm that each of these IDs is assigned to an existing element. For example:

        <button id="addPhoneButton">Add Phone</button>
        <img id="qrcode2" class="d-none" src="" alt="QR Code">
        <!-- More elements... -->
        
    3. Check for Typos:

      • Ensure that the IDs in your JavaScript exactly match those in your HTML. Even a minor difference (like qrcode2 vs. qrCode2) can cause issues.
    4. Ensure Elements Are Loaded:

      • Since you're using DOMContentLoaded, the elements should be available. However, if elements are loaded dynamically (e.g., via AJAX or other scripts), ensure that your code accounts for their asynchronous loading.
    5. Add Defensive Coding:

      • Before manipulating an element, check if it exists to prevent the script from crashing.
        const addPhoneButton = document.getElementById('addPhoneButton');
        if (addPhoneButton) {
          addPhoneButton.addEventListener('click', function() {
            addPhoneRequest();
          });
        } else {
          console.error('Element with ID "addPhoneButton" not found.');
        }
        
      • Repeat similar checks for other critical elements.
    6. Utilize Console Logging:

      • Add console.log statements before each getElementById to verify element retrieval.
        console.log('Attempting to access addPhoneButton:', document.getElementById('addPhoneButton'));
        
    7. Review Asynchronous Code:

      • Ensure that any asynchronous operations (like AJAX calls) don't interfere with the availability of required DOM elements.
    8. Check for Duplicate IDs:

      • Ensure that each ID is unique within the HTML document. Duplicate IDs can cause unexpected behaviors.

    Example Fix:

    Suppose the error points to the following line in your JavaScript:

    document.getElementById("qrcode2").classList.remove("d-block");
    

    Steps to Fix:

    1. Verify HTML:

      • Ensure there's an element with id="qrcode2".
        <img id="qrcode2" class="d-none" src="" alt="QR Code">
        
    2. Add Defensive Check:

      const qrcode2Element = document.getElementById("qrcode2");
      if (qrcode2Element) {
        qrcode2Element.classList.remove("d-block");
        qrcode2Element.classList.add("d-none");
      } else {
        console.error('Element with ID "qrcode2" not found.');
      }
      

    Additional Recommendations:

    1. Use querySelector with Classes or Data Attributes:

      • For more flexibility and to reduce reliance on unique IDs, consider using classes or data- attributes.
        document.querySelector('.qrcode2').classList.remove('d-block');
        
    2. Modularize Your Code:

      • Break down your JavaScript into smaller, reusable functions. This makes it easier to manage and debug.
    3. Leverage Modern JavaScript Features:

      • Consider using let and const appropriately, arrow functions for cleaner syntax, and other ES6+ features to enhance readability.
    4. Use JavaScript Frameworks or Libraries:

      • Libraries like React, Vue, or frameworks like Laravel Blade (if you're using Laravel) can help manage DOM elements more effectively and reduce such errors.
    5. Automated Testing:

      • Implement tests to ensure that all necessary DOM elements are present and correctly initialized before user interactions.

    Conclusion

    The key to resolving the Uncaught TypeError: document.getElementById(...) is null error lies in ensuring that all DOM elements your JavaScript interacts with are present and correctly identified in your HTML. By systematically verifying each element and adding defensive checks, you can prevent these errors and ensure smooth execution of your scripts.

    If after these steps the issue persists, please provide the relevant segments of your HTML where these elements are defined, and specify which getElementById call is causing the error. This will allow for more targeted assistance.