Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda