I am trying to handle a ajax request using expressjs, when i click the any anchor tag then the page fully reloads and didn’t get the hand ajax request on client side. I need when i click any of these link then it should handle by client side using fetch api
This is html stucture
<header id="main-header">
<nav>
<ul>
<li class="nav-bar"><a data-urlid="" href="/">Home</a></li>
<li class="nav-bar"><a data-urlid="about" href="/about">About</a></li>
<li class="nav-bar"><a data-urlid="achievements" href="/achievements">Achievements</a></li>
<li class="nav-bar"><a data-urlid="gallery" href="/gallery">Gallery</a></li>
<li class="nav-bar"><a data-urlid="contact" href="/contact">Contact</a></li>
</ul>
</nav>
</header>
This is controller
const home = (req, res) => {
res.json({message:"success"})
};
this is router for get home page
router.get("/", danceController.home);
Trying to handle ajax request using vanilla js
const navBars = document.querySelectorAll(".nav-bar");
async function head(event) {
event.preventDefault();
const url = event.target.dataset.urlid;
const responseData = await fetch(`/${url}`, {
method: "GET",
headers: {"Content-Type":"text/html"}}).then((response) => {
console.log(response);
});
// console.log(responseData);
};
for (const navBar of navBars) {
navBar.addEventListener("click", head)
}