CMS Development

soorajvtrio
Member

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

On the website https://belong.naifa.org, the "Member Spotlight" section located above the footer is sometimes not loading properly.

 

We've developed a custom module that fetches data from : https://members.naifa.org/member-spotlights, but occasionally it displays an error message (please see the attached screenshot).

loading-error.png

 

Here the code that we have used in the custom module:

 

<div class="spotlight-wrapper">
<div class="spotlight-title">Member Spotlights</div>
<div id="loader" class="loader">
<div class="spinner"></div>
</div>
<div id="spotlight-list" class="article-cards spotlights-container" style="display: none;">
<!-- Spotlight content will be injected here -->
</div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
const spotlightContainer = document.getElementById('spotlight-list');
const loader = document.getElementById('loader');

const url = "https://api.allorigins.win/raw?url=" + encodeURIComponent("https://members.naifa.org/member-spotlights");

fetch(url)
.then(response => response.text())
.then(html => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const events = doc.querySelectorAll(".main-box");

if (events.length === 0) {
loader.innerHTML = "<p>No spotlight content available.</p>";
return;
}

spotlightContainer.innerHTML = "";

events.forEach((event, index) => {
if (index >= 3) return;

const image = event.querySelector(".hs_cos_wrapper img")?.src || "";
let strongs = event.querySelectorAll("p strong");
let name = strongs[0]?.innerHTML || "";
let subtitle = strongs.length > 1 ? strongs[1].innerHTML : "";

let title = `<span class="name">${name}</span><span class="subtitle">${subtitle}</span>`;

let anchor = event.querySelector("a[href*='member-spotlight']");
let link = "#";
if (anchor) {
let rawHref = anchor.getAttribute("href") || "#";
try {
link = new URL(rawHref, "https://at.naifa.org").href;
} catch (err) {
console.warn("Invalid link:", rawHref);
}
}

spotlightContainer.innerHTML += `
<div class="article-card">
<div class="article-image">
<img src="${image}" alt="${name}">
</div>
<div class="article-text">
<h2>${title}</h2>
<a href="${link}" class="read-more" rel="noopener">Read More →</a>
</div>
</div>
`;
});

loader.style.display = "none";
spotlightContainer.style.display = "flex";
})
.catch(error => {
console.error('Error loading spotlight content:', error);
loader.innerHTML = '<p>Spotlight content is currently unavailable. Please check back later.</p>';
});
});
</script>

 

Could you please help in resolving this issue.

 

0 Upvotes
1 Accepted solution
nickdeckerdevs1
Solution
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

All the code below is AI generated, making sure to include the console errors in it after three attempts. I'd review the code before implementing, but basically what it is doing is trying every 800ms and checkint to see if teh max retries have happened, if after the three attempts happens, then it reports the error to the screen and the error details to the console

You will only be able to understand what the actual error is if you are on the page when the error happens

 

<div class="spotlight-wrapper">
    <div class="spotlight-title">Member Spotlights</div>
    <div id="loader" class="loader">
        <div class="spinner"></div>
    </div>
    <div id="spotlight-list" class="article-cards spotlights-container" style="display: none;">
        <!-- Spotlight content will be injected here -->
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const spotlightContainer = document.getElementById('spotlight-list')
        const loader = document.getElementById('loader')

        const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

        async function fetchWithRetry(url, maxRetries = 3, delayMs = 800) {
            let lastError

            for (let attempt = 1; attempt <= maxRetries; attempt++) {
                try {
                    const response = await fetch(url)
                    return await response.text()
                } catch (error) {
                    lastError = error
                    if (attempt < maxRetries) {
                        await delay(delayMs)
                    }
                }
            }
            throw lastError
        }

        async function loadSpotlights() {
            const url = "https://api.allorigins.win/raw?url=" + encodeURIComponent("https://members.naifa.org/member-spotlights")

            try {
                const html = await fetchWithRetry(url)
                const parser = new DOMParser()
                const doc = parser.parseFromString(html, "text/html")
                const events = doc.querySelectorAll(".main-box")

                if (events.length === 0) {
                    loader.innerHTML = "<p>No spotlight content available.</p>"
                    return
                }

                spotlightContainer.innerHTML = ""

                events.forEach((event, index) => {
                    if (index >= 3) return

                    const image = event.querySelector(".hs_cos_wrapper img")?.src || ""
                    let strongs = event.querySelectorAll("p strong")
                    let name = strongs[0]?.innerHTML || ""
                    let subtitle = strongs.length > 1 ? strongs[1].innerHTML : ""

                    let title = `<span class="name">${name}</span><span class="subtitle">${subtitle}</span>`

                    let anchor = event.querySelector("a[href*='member-spotlight']")
                    let link = "#"
                    if (anchor) {
                        let rawHref = anchor.getAttribute("href") || "#"
                        try {
                            link = new URL(rawHref, "https://at.naifa.org").href
                        } catch (err) {
                            console.warn("Invalid link:", rawHref)
                        }
                    }

                    spotlightContainer.innerHTML += `
                        <div class="article-card">
                            <div class="article-image">
                                <img src="${image}" alt="${name}">
                            </div>
                            <div class="article-text">
                                <h2>${title}</h2>
                                <a href="${link}" class="read-more" rel="noopener">Read More →</a>
                            </div>
                        </div>
                    `
                })

                loader.style.display = "none"
                spotlightContainer.style.display = "flex"
            } catch (error) {
                console.error('Error details:')
                console.log(error)
                console.log('message')
                console.log(error.message)
                console.log('name')
                console.log(error.name)
                console.log('stack')
                console.log(error.stack)
                console.log('url')
                console.log(url)
                console.log('new Date().toISOString()')
                console.log(new Date().toISOString())

                console.error('Error loading spotlight content:', error)
                loader.innerHTML = '<p>Spotlight content is currently unavailable. Please check back later.</p>'
            }
        }

        loadSpotlights()
    })
</script>

 

View solution in original post

0 Upvotes
6 Replies 6
nickdeckerdevs1
Solution
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

All the code below is AI generated, making sure to include the console errors in it after three attempts. I'd review the code before implementing, but basically what it is doing is trying every 800ms and checkint to see if teh max retries have happened, if after the three attempts happens, then it reports the error to the screen and the error details to the console

You will only be able to understand what the actual error is if you are on the page when the error happens

 

<div class="spotlight-wrapper">
    <div class="spotlight-title">Member Spotlights</div>
    <div id="loader" class="loader">
        <div class="spinner"></div>
    </div>
    <div id="spotlight-list" class="article-cards spotlights-container" style="display: none;">
        <!-- Spotlight content will be injected here -->
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const spotlightContainer = document.getElementById('spotlight-list')
        const loader = document.getElementById('loader')

        const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

        async function fetchWithRetry(url, maxRetries = 3, delayMs = 800) {
            let lastError

            for (let attempt = 1; attempt <= maxRetries; attempt++) {
                try {
                    const response = await fetch(url)
                    return await response.text()
                } catch (error) {
                    lastError = error
                    if (attempt < maxRetries) {
                        await delay(delayMs)
                    }
                }
            }
            throw lastError
        }

        async function loadSpotlights() {
            const url = "https://api.allorigins.win/raw?url=" + encodeURIComponent("https://members.naifa.org/member-spotlights")

            try {
                const html = await fetchWithRetry(url)
                const parser = new DOMParser()
                const doc = parser.parseFromString(html, "text/html")
                const events = doc.querySelectorAll(".main-box")

                if (events.length === 0) {
                    loader.innerHTML = "<p>No spotlight content available.</p>"
                    return
                }

                spotlightContainer.innerHTML = ""

                events.forEach((event, index) => {
                    if (index >= 3) return

                    const image = event.querySelector(".hs_cos_wrapper img")?.src || ""
                    let strongs = event.querySelectorAll("p strong")
                    let name = strongs[0]?.innerHTML || ""
                    let subtitle = strongs.length > 1 ? strongs[1].innerHTML : ""

                    let title = `<span class="name">${name}</span><span class="subtitle">${subtitle}</span>`

                    let anchor = event.querySelector("a[href*='member-spotlight']")
                    let link = "#"
                    if (anchor) {
                        let rawHref = anchor.getAttribute("href") || "#"
                        try {
                            link = new URL(rawHref, "https://at.naifa.org").href
                        } catch (err) {
                            console.warn("Invalid link:", rawHref)
                        }
                    }

                    spotlightContainer.innerHTML += `
                        <div class="article-card">
                            <div class="article-image">
                                <img src="${image}" alt="${name}">
                            </div>
                            <div class="article-text">
                                <h2>${title}</h2>
                                <a href="${link}" class="read-more" rel="noopener">Read More →</a>
                            </div>
                        </div>
                    `
                })

                loader.style.display = "none"
                spotlightContainer.style.display = "flex"
            } catch (error) {
                console.error('Error details:')
                console.log(error)
                console.log('message')
                console.log(error.message)
                console.log('name')
                console.log(error.name)
                console.log('stack')
                console.log(error.stack)
                console.log('url')
                console.log(url)
                console.log('new Date().toISOString()')
                console.log(new Date().toISOString())

                console.error('Error loading spotlight content:', error)
                loader.innerHTML = '<p>Spotlight content is currently unavailable. Please check back later.</p>'
            }
        }

        loadSpotlights()
    })
</script>

 

0 Upvotes
soorajvtrio
Member

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

Hi @nickdeckerdevs1 , thanks for the updated code.  I’ll test the code and let you know how it goes. Appreciate your support!

0 Upvotes
Jaycee_Lewis
Community Manager
Community Manager

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

Thank you @nickdeckerdevs1 🙌 — Jaycee


HubSpot’s AI-powered customer agent resolves up to 50% of customer queries instantly, with some customers reaching up to 90% resolution rates.
Learn More.


Did you know that the Community is available in other languages?
Join regional conversations by changing your language settings !
0 Upvotes
nickdeckerdevs1
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

Unfortunatly we can't determine what the acutal error is..

You would need to understan the error that is being ouput from the fetch call -- you can debug this in the console in dev tools, you could also add the following to your catch to improve what you need to look at.

console.error('Error details:')
console.log(error)
console.log('message')
console.log(error.message)
console.log('name')
console.log(error.name)
console.log('stack')
console.log(error.stack)
console.log('url')
console.log(url)
console.log('new Date().toISOString()')
console.log(new Date().toISOString())

 

Depending on the error, you may want to have it retry if there is an error -- so having some sort of variable for calls made to the api

If this is just some random failure, it might be worth counting the errors, and recalling the function to fetch the data. That would take some reworking of your code to make it so that the functions are seperated out....

let me know how else I can help and where you are getting stuck at

nickdeckerdevs1
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

Adding the code here in a code block so that it is readable

<div class="spotlight-wrapper">
    <div class="spotlight-title">Member Spotlights</div>
    <div id="loader" class="loader">
        <div class="spinner"></div>
    </div>
    <div id="spotlight-list" class="article-cards spotlights-container" style="display: none;">
        <!-- Spotlight content will be injected here -->
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const spotlightContainer = document.getElementById('spotlight-list')
        const loader = document.getElementById('loader')

        const url = "https://api.allorigins.win/raw?url=" + encodeURIComponent("https://members.naifa.org/member-spotlights")

        fetch(url)
            .then(response => response.text())
            .then(html => {
                const parser = new DOMParser()
                const doc = parser.parseFromString(html, "text/html")
                const events = doc.querySelectorAll(".main-box")

                if (events.length === 0) {
                    loader.innerHTML = "<p>No spotlight content available.</p>"
                    return
                }

                spotlightContainer.innerHTML = ""

                events.forEach((event, index) => {
                    if (index >= 3) return

                    const image = event.querySelector(".hs_cos_wrapper img")?.src || ""
                    let strongs = event.querySelectorAll("p strong")
                    let name = strongs[0]?.innerHTML || ""
                    let subtitle = strongs.length > 1 ? strongs[1].innerHTML : ""

                    let title = `<span class="name">${name}</span><span class="subtitle">${subtitle}</span>`

                    let anchor = event.querySelector("a[href*='member-spotlight']")
                    let link = "#"
                    if (anchor) {
                        let rawHref = anchor.getAttribute("href") || "#"
                        try {
                            link = new URL(rawHref, "https://at.naifa.org").href
                        } catch (err) {
                            console.warn("Invalid link:", rawHref)
                        }
                    }

                    spotlightContainer.innerHTML += `
                        <div class="article-card">
                            <div class="article-image">
                                <img src="${image}" alt="${name}">
                            </div>
                            <div class="article-text">
                                <h2>${title}</h2>
                                <a href="${link}" class="read-more" rel="noopener">Read More →</a>
                            </div>
                        </div>
                    `
                })

                loader.style.display = "none"
                spotlightContainer.style.display = "flex"
            })
            .catch(error => {
                console.error('Error loading spotlight content:', error)
                loader.innerHTML = '<p>Spotlight content is currently unavailable. Please check back later.</p>'
            })
    })
</script>
0 Upvotes
Jaycee_Lewis
Community Manager
Community Manager

Issue with Custom Module Fetching "Member Spotlight" Data on Belong.naifa.org

SOLVE

Hey, @soorajvtrio 👋 Thanks for your post and for including your details. This one is tough to troubleshoot. I'd like to offer a few high-level suggestions and troubleshooting steps. Hopefully, this will help get you unstuck and give our community members more information. 

 

Suggestions:

Implement Content Caching

  • store successfully fetched content in `localStorage` with an expiration time
  • fall back to cached content when new fetches fail
  • to provide a better experience during temporary outages

Error Handling

  • add timeouts to prevent indefinite loading states

CORS issues

  • do we have any way to know if the allorigins.win service experiencing reliability issues
  • Serverless functions might be a more reliable proxy

 

Troubleshooting:

Check Browser Console

  • is there anything unexpected or interesting here when the content fails to load?

Patterns

  • does the error occur at specific times of day?
  • is it happening on particular browsers or devices?

Validate

  • has the source page structure at members.naifa.org has changed?
  • can you manually navigate to the source page works when the error occurs?

 

Remember that with community troubleshooting, providing more details about when and how the error occurs will help others provide more targeted assistance.​​​​​​​​​​​​​​​​

 

Talk soon! — Jaycee


HubSpot’s AI-powered customer agent resolves up to 50% of customer queries instantly, with some customers reaching up to 90% resolution rates.
Learn More.


Did you know that the Community is available in other languages?
Join regional conversations by changing your language settings !
0 Upvotes