Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
Making a single page application with ajax and get a 404 error when the page is reloaded

Basically, I'm coding a personal website and have made a single page application with ajax so content is added to the page between the header and footer when a page in the navigation bar is clicked. I had to manually code the push state and pop state in order to get the back and forward arrows working, which they do. However, the only issue left is that when I reload the page, I get an entry not found error.

I'm very new to web dev and javascript so some of my code is a little messy. I know the reload issue has to do with the added page URL not actually existing on the server.

Here are the relevant pieces of my code:

HTML:

<nav>
   <ul class='nav-bar'>
      <li class='nav-item'><a id='writing'>Writing</a></li>
      <li class='nav-item'><a id='editing'>Editing</a></li>
      <li class='nav-item'><a id='about'>About</a></li>
      <li class='nav-item'><a id='contact'>Contact</a></li>
   </ul>
</nav>

Javascript

//change page on nav click
    $('.nav-bar li a').on('click', function(e) {
        e.preventDefault();
        var page = $(this).attr('id');
        var file = page + '.html';
        var origin = window.location.origin;
        //nav color change for current page
        removeActiveLinks();
        $(this).parent().addClass("active");

        $.ajax({
            type: 'GET',
            url: origin,
            dataType: 'html',
            success: function(response) {
                $('#content').load(file);
            },

            error: function(error) {
                console.log('There was an error', error);
            }
        });
        window.history.pushState(file, null, '/' + page);
    });

    //nav for home page
    $('#home').on('click', function(e) {
        e.preventDefault();
        removeActiveLinks();
        $('#content').load('home.html')

        window.history.pushState('index.html', null, '/');
    });

    //ensure page back functionality
    window.addEventListener('popstate', function(event) {
        var prevState = event.state;
        $('#content').load(prevState);
        removeActiveLinks();

        var page_id = '#' + prevState.split('.')[0];
        $(page_id).parent().addClass('active');
    });

Here's what the error looks like

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I would suggest something simpler, using simple load() (shorthand for ajax) and a the state of the history directly.

Not tested, but should work fine.

// Initial page load
$(document).ready(function(){
  $("#content").load("home.html");
})

// Change page on nav click
$(".nav-bar li a, #home").on("click", function (e) {
  e.preventDefault();
  
  var file = this.id + ".html";

  //nav color change for current page
  $(".active").removeClass("active");
  if(this.id != "home"){
    $("#"+this.id).parent().addClass("active");
  }

  $("#content").load(file);
  window.history.pushState(file, null, "/");
});

// Ensure page back functionality
window.addEventListener("popstate", function (event) {
  var prevState = event.state;
  $("#content").load(prevState);

  var page_id = "#" + prevState.split(".")[0];
  $(".active").removeClass("active");

  if(page_id != "#home"){
    $(page_id).parent().addClass("active");
  }
});

But there is no /writing in the adress bar with this solution. If you insist on it, you will have to dive in more complex route settings on the server.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda