Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laravel_ninja's avatar

JavaScript fetch cause unwanted page reload

I am fetching posts from my Laravel project using fetch api . Each time request goes to the server my page gets reload I'm using fetch api to request .

console.log(`Go and try to fetch data from API'S`);
const table = document.querySelector("#fetch-data");
const fetchBtn = document.querySelector("#fetch-button");
console.log(table);
console.log(fetchBtn);
const BASE_URL = "http://127.0.0.1:8000/api/posts";

fetchBtn.addEventListener("click", (event) => {
  event.preventDefault();
  fetchPosts();
});

const fetchPosts = () => {
  fetch(`${BASE_URL}`)
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      const posts = json.posts;
      updateDom(posts);
      console.log(json);
    })
    .catch(function (err) {
      console.log(err);
    });
};

const updateDom = (posts) => {
  let li = `<tr><th>Post Title</th><th>Post Content</th></tr>`;
  posts.forEach((post) => {
    li += `<tr>
        <td>${post.title} </td>
        <td>${post.content}</td>        
    </tr>`;
  });
  table.innerHTML = li;
};

Here is the backend

Route::apiResource('posts', PostController::class);
public function index()
    {
        return response()->json([
            'status' => 'Success',
            'posts' => Post::all(),
        ]);
    }
0 likes
4 replies
Sinnbeck's avatar

And the button code? And why not do

document.getElementById("fetch-button");
laravel_ninja's avatar

@Sinnbeck

<button id="fetch-button">Fetch</button>

Here is the button code I don't know why on each request page gets reload

Please or to participate in this conversation.