1

I am trying to handle a ajax request using ExpressJS, but when I click on any anchor tag, the page fully reloads and do not get the hand ajax request on client side.

I need that when I click on any of these links, 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)
}
Pablo Sarturi
  • 161
  • 1
  • 10
  • 1
    @jabaa — That goes against the principle of [Unobtrusive JS](https://en.wikipedia.org/wiki/Unobtrusive_JavaScript) and shouldn't be needed given the code uses `event.preventDefault`. – Quentin Dec 17 '21 at 11:56
  • Log `navBars`. It is probably empty. This is probably a duplicate of https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element but you didn't show us the relationship between the HTML you did show us and the ` – Quentin Dec 17 '21 at 11:57
  • Your question title is very misleading BTW. The problem is that you aren't making the Ajax request in the first place. There's currently nothing to handle. – Quentin Dec 17 '21 at 11:58
  • `headers: {"Content-Type":"text/html"}` makes no sense. You are making a GET request with no request body therefore the request body but that code claims that the non-existent request body is an HTML document. – Quentin Dec 17 '21 at 11:58

1 Answers1

0

Try replacing the hrefs with '#', then you'll need to parse the response from JSON before logging it to the console, ie responseData should look something more like this:

const responseData = await fetch(`/${url}`)
                           .then(response => response.json())
                           .then(response => {
                               console.log(response);
                           });

If it's still not working, make sure the expected version of the JS is being loaded by the browser.

Austin
  • 1