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

151
Visualizações
How to redirect to page with history API on popstate when submit a form with ajax?

I have an issue when using history API on form submission with Ajax, I want to automatically redirected with historyRender() when the request is successfully, but since it takes the window pop state event it does not do anything. I want function HistoryRender(url) to work work when is initialized without any click event.

How can I work it automatically with the passed URL without clicking anything on a document

//my HTML form

<form method="post" action="send.php" id="jsForm">
    <input type="text" name="name" id="name">
    <button type="submit">Save</button>
</form>

//my ajax

    $(document).on('submit', '#jsForm', function(e){
        e.preventDefault();
        let $url = $(this).attr('action'),
            $req;
            $req = $.ajax({
                url: $url,
                method: 'post',
                data: $(this).serialize(),
                dataType: 'html',
            });
            $req.done((data) =>{   
                let $data  = data;
                historyRender('/url-redirect');
            }); 
            $req.fail((message, err, status)=>{
                console.log("request failed" + message);
            })      

    });

//history api

function historyRender(element = 'a', attr = 'href'){
    $(document).on('click', element, function(e){
        e.preventDefault();
        let href = attr;
        //------ user goback and forward -----------
        window.onpopstate = function(e){
            if(e.state)
                ajaxRender(e.state.href);
        };
        //---------------push state
        window.history.pushState({href: href}, '', href);    
        ajaxRender(href);
    });
}

function ajaxRender(href){
    let  $url = href, req;
    req = $.ajax({
        url: $url,
        method: 'GET',
        cache: false,
        dataType: 'html',
    });
    req.done((data) =>{   
        let $data  = data, 
            $res   = $data, 
            $title = $res.filter('title').text().trim();
   
        if($data)
            $('title').text($title);
            ($title) ? $('body').html($data) : $('body').html($data); 
    });
}
about 4 years ago · Juan Pablo Isaza
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